用htaccess替换问号和等号

时间:2013-09-03 02:19:45

标签: php apache .htaccess url url-rewriting

我正在尝试替换问号和等号,以便我可以使用以下网址:

http://www.mydomain.com/categories/id/23/name/category-name

以上网址将在内部重定向到 http://www.mydomain.com/categories?id=23&name=category-name

我正在使用.htaccess:

Options +FollowSymLinks -MultiViews
RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

# external redirect from /view.php?id=1 to /view/id/1
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+([^.]+)\.php\?([^=]+)=([^\s&]+) [NC]
RewriteRule ^ /%1/%2/%3? [L,R=301]

# internal forward from /view/id/1 to /view.php?id=1
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ /$1.php?$2=$3 [L,QSA]

但它没有按预期工作。当我转到http://www.mydomain.com/categories/id/23/name/category-name时,我收到500内部服务器错误。为什么?我做错了什么?

更新代码

Options +FollowSymLinks -MultiViews
RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?(.*)$ $1/$2=$3&$4 [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^/]+)/([^/]+)$ $1.php?$2 [L,QSA] 

1 个答案:

答案 0 :(得分:1)

此规则应该负责以/递归替换每个=,最后使其成为一个很好的查询字符串:

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?(.*)$ $1/$2=$3&$4 [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{DOCUMENT_ROOT}/$1.php -f
RewriteRule ^([^/]+)/([^/]+)$ $1.php?$2 [L,QSA]

您需要注释掉或删除此规则:

# RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ /$1.php?$2=$3 [L,QSA]

更新:你.htaccess需要重新排序和一点点调整。这应该有效:

Options +FollowSymLinks -MultiViews
RewriteEngine on
RewriteBase /mydomain/

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?(.*)$ $1/$2=$3&$4 [L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^/]+)/(.+?)&?$ $1.php?$2 [L,QSA] 

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]