【问题标题】:multiple mod_rewrite rules in .htaccess.htaccess 中的多个 mod_rewrite 规则
【发布时间】:2012-04-22 18:20:03
【问题描述】:

我很难让多个 mod_rewrite 规则在我的 .htaccess 文件中协同工作。在整个网站中,我想删除“www”。来自所有 URL。我在文档根目录使用以下内容:

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

所以在 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

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

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

【问题讨论】:

  • apache 错误日志是怎么说的?

标签: apache .htaccess mod-rewrite


【解决方案1】:

看起来正在发生的事情是 /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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-31
    • 2015-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多