.htaccess中的多个mod_rewrite规则

时间:2012-04-10 12:47:20

标签: apache .htaccess mod-rewrite

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

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

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

  1. 将domain.com/help/1 更改为 domain.com/index.php?question=1
  2. 将domain.com/help/category/example 更改为 domain.com/index.php?category=example
  3. 所以在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 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文件中?

1 个答案:

答案 0 :(得分:2)

看起来正在发生的是 / 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友好的网址,那么这可能不是您想要的。

您最好的选择可能是将 / 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

相关问题