用mod_rewrite重写2级url

时间:2012-05-27 01:55:21

标签: apache .htaccess mod-rewrite

我需要这样的东西 index.php?page = home to be home

index.php?page = products& cat = chair to be / products / chairs

实现此目的的mod_rewrite规则是什么? 谢谢

============== EDITED 我有其他页面而不是家,所以我的.htaccess文件的完整内容现在是

RewriteEngine On
RewriteRule ^([^/\.]+)/?$ index.php?page=$1 [L]
RewriteRule   ^/products(:/([^/]+))?   /index.php?page=products&cat=$1 [L]

但是当我导航到 / products / chairs我发现Object not found错误。

2 个答案:

答案 0 :(得分:0)

RewriteEngine on
RewriteRule   ^/home/?$                /index.php?page=home [L]
RewriteRule   ^/products(:/([^/]+))?   /index.php?page=products&cat=$1 [L]

它重写了/home/home//products/products/(你没有指明你的预期行为);请注意,在这些情况下,您将获得一个空的cat参数。

编辑:这是一个经过测试的.htaccess,其上还有R = 301以查看重写结果,同一目录中的.htaccess和index.php(在我的情况下是webroot):

RewriteEngine on
RewriteRule ^([^/\.]+)/?$          index.php?page=$1 [R=301,L]
RewriteRule ^products/([^/]+)?/?   index.php?page=products&cat=$1 [R=301,L]

答案 1 :(得分:0)

通过httpd.conf启用mod_rewrite和.htaccess,然后将此代码放在.htaccess目录下的DOCUMENT_ROOT中:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?page=(products)&cat=([^\s]+) [NC]
RewriteRule ^ %1/%2 [R=302,L]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+index\.php\?page=(home)\s [NC]
RewriteRule ^ %1 [R=302,L]

RewriteRule   ^(products)/([^/]+)/?$ index.php?page=(products)&cat=$1 [L,QSA,NC]

RewriteRule   ^(home)/?$ index.php?page=$1 [L,QSA,NC]

在您确认其工作正常后,将R=302更改为R=301