【问题标题】:Rewrite rule to work consistently for subdomain and subdirectory重写规则以一致地为子域和子目录工作
【发布时间】:2013-03-26 16:09:20
【问题描述】:

我有一个很好的规则来将 url 重写为 /meetings,但是当从子目录访问时,该规则不会正确地重写 url。

编辑:我的 .htaccess 文件位于 /blog 子目录中

当我使用这条规则时:...

RewriteRule ^meetings$ /?page_id=2809 [L]

从子域访问时(blog.example.com/meetings):blog.example.com/meetings

从子目录访问时 (example.com/blog/meetings):404 错误

当我使用这条规则时:...

RewriteRule ^meetings$ http://blog.example.com/?page_id=2809 [L]

从子域访问时(blog.example.com/meetings):blog.example.com/meetings

从子目录 (example.com/blog/meetings) 访问时:blog.example.com/?page_id=2809

有没有办法让规则在子域和子目录中保持一致?

【问题讨论】:

  • 您请求的 URL 是什么?请更新问题。
  • 只是 blog.example.com/meetings 和 example.com/blog/meetings。

标签: .htaccess mod-rewrite


【解决方案1】:

您可以在/blog 目录中的一个 .htaccess 文件中尝试此操作:

Options +FollowSymlinks -MultiViews
RewriteEngine On
RewriteBase /blog

RewriteCond %{HTTP_HOST}      blog\.example\.com               [NC]
RewriteCond %{QUERY_STRING}   !page_id=                        [NC]
RewriteRule ^meetings         /?page_id=2809                   [L,NC]

RewriteCond %{HTTP_HOST}      ^(www\.)?example\.com            [NC]
RewriteCond %{QUERY_STRING}   !page_id=                        [NC]
RewriteRule ^meetings         /blog/?page_id=2809              [L,NC]

对于永久重定向,请将 [L,NC] 替换为 [R=301,L,NC]。

【讨论】:

  • 从 `blog.example.com/meetings' 访问时我得到“未找到”
  • 添加了前导斜杠。请再试一次。如果仍然不起作用,请回答 2 个问题:example.com/meetings 是否按预期工作,blog 是托管在 example.com/blog 的插件子域吗?
  • 这成功了!您能否解释一下为什么需要 RewriteCond 以及 -MultiViews 到底是做什么的?非常感谢!
  • MultiViews 允许资源协商,最好解释here。 mod_rewrite 在启用该选项的情况下无法正常工作,这就是为什么禁用它以使用该模块很重要。 RewriteCond 用于选择请求的主机并相应地应用规则,并防止循环 (!page_id=)。
猜你喜欢
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多