apache – .htaccess中的多个mod_rewrite规则

我很难获得几个mod_rewrite规则在我的.htaccess文件中一起工作.在enitre网站上,我想删除“www”.来自所有网址.我在文档根目录中使用以下内容:

Options +FollowSymLinks
RewriteCond %{HTTP_HOST} ^www\.(.+)$[NC]
RewriteRule ^(.*)$http://%1/$1 [R=301]

然后,在一个文件夹“/ help”中我想做2次重写:

>将domain.com/help/1更改为domain.com/index.php?question=1
>将domain.com/help/category/example更改为domain.com/index.php?category=example

所以在domain.com/help我有以下内容:

Options +FollowSymLinks
RewriteRule ^([0-9]+)/?$index.php?question=$1 [NC,L]
RewriteRule ^category/([^/\.]+)/?$index.php?category=$1 [NC,L]

以上2 .htaccess文件适用于:
www.domain.com到domain.com
domain.com/help/1到domain.com/index.php?question=1
domain.com/help/category/example to domain.com/index.php?category=example

但是,当我需要将两次重写合并为两个“www”时,这不起作用.并将子文件夹重写为url变量.例如.:
www.domain.com/help/1到domain.com/index.php?question=1
给出500错误.

我哪里做错了?并且,这最好是使用2 .htaccess文件,还是可以/应该将2个文件合并到文档根目录下的1 .htaccess文件中?

最佳答案 看起来正在发生的事情是/ help文件夹中的.htaccess文件中的规则正在应用,因为您正在请求该文件夹中的某些内容,因此不会应用父文件夹的规则.如果在/ help文件夹的.htaccess中添加RewriteOptions Inherit,则可以传递父规则:

Options +FollowSymLinks
RewriteOptions Inherit
RewriteRule ^([0-9]+)/?$index.php?question=$1 [NC,L]
RewriteRule ^category/([^/\.]+)/?$index.php?category=$1 [NC,L]

但是,继承的规则可能不会按您期望的顺序应用.例如,如果您请求http://www.domain.com/help/1/,您最终会被重定向到http://domain.com/index.php?question=1,如果您试图通过隐藏查询字符串来创建SEO友好URL,则可能不是您想要的.

您最好的选择可能是将/ help文件夹中的内容移动到文档根目录中,以便您可以控制规则的应用顺序:

Options +FollowSymLinks

RewriteCond %{HTTP_HOST} ^www\.(.+)$[NC]
RewriteRule ^(.*)$http://%1/$1 [R=301]

RewriteRule ^help/([0-9]+)/?$/index.php?question=$1 [NC,L]
RewriteRule ^help/category/([^/\.]+)/?$/index.php?category=$1 [NC,L]

这样可以确保首先重定向到非www域,然后应用/ help规则.因此,当您转到http://www.domain.com/help/1/时,首先会将您重定向到http://domain.com/help/1/,然后应用帮助规则并将URI重写为/index.php?question=1.

点赞