apache - .htaccess 中的多个 mod_rewrite 规则

标签 apache .htaccess mod-rewrite

我很难让几个 mod_rewrite 规则在我的 .htaccess 文件中一起工作。在整个站点中,我想去掉“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 域名.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 文件中?

    最佳答案

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

    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,这可能不是您想要的。

    最好的办法可能是移动 中的内容。/帮助 文件夹放入文档根目录中的文件夹,以便您可以控制应用规则的顺序:
    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 域,然后是 /帮助 规则得到应用。所以当你去http://www.domain.com/help/1/ , 你首先被重定向到 http://domain.com/help/1/然后应用帮助规则,URI 被重写为 /index.php?question=1 .

    关于apache - .htaccess 中的多个 mod_rewrite 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10089097/

    相关文章:

    mod-rewrite - nginx 重写 : everything but empty base url

    apache - 以编程方式将用户名和密码发送到 Apache Web 服务器

    apache - tomcat 7应用迁移到tomcat 8

    apache - JOOMLA 网站速度太慢

    wordpress - MOD_REWRITE/foo.html 到/existing/page/?page=foo

    apache - cakephp 在 Ubuntu 上无法进行 url 重写

    apache - 如何禁用 DirectoryIndexRedirect

    java - 文件处理中的 Apache Avro

    .htaccess - 检测和重定向支持 SNI 的浏览器的最有效代码是什么?

    php - 帮助 PHP 的 Bootstrap 和正则表达式