【问题标题】:Using RewriteCond to match only a page or a directory having the same name使用 RewriteCond 仅匹配具有相同名称的页面或目录
【发布时间】:2021-09-03 03:46:14
【问题描述】:

我正在尝试使用.htaccess 重定向文件和文件夹。我想在RewriteRule 之前添加一个RewriteCond 指令以仅匹配example.com/place/sta-ana.htmlexample.com/place/sta-ana 目录。我试过这个:

RewriteCond %{REQUEST_URI} ^place/sta-ana(\.html|/.*)?
RewriteRule ^place/sta-ana(\.html|/.*)? /place/santa-ana$1 [L,NC,R=301]

还有这个:

RewriteCond %{THE_REQUEST} ^place/sta-ana(\.html|/.*)?
RewriteRule ^place/sta-ana(\.html|/.*)? /place/santa-ana$1 [L,NC,R=301]

但两者都只适用于重定向place/sta-ana.html 而不是目录及其文件,如place/sta-ana/santiago.htmlplace/sta-ana/santiago/lourdes.html。我怎样才能获得上面的代码也将sta-ana 目录重定向到santa-ana 文件夹:

example.com/place/sta-ana.html => example.com/place/santa-ana.html
example.com/place/sta-ana/santiago.html => example.com/place/santa-ana/santiago.html
example.com/place/sta-ana/santiago/lourdes.html => example.com/place/santa-ana/santiago/lourdes.html

【问题讨论】:

  • 是否要将example.com/place/sta-ana/子目录中的所有文件重定向到/place/santa-ana/$1
  • 你能写几个源 URL 和目标 URL 的例子吗?例如,不清楚 example.com/place/sta-ana.html 的目标 URL 是什么
  • @anubhava,是的,除了example.com/place/sta-ana.html 重定向到example.com/place/santa-ana.html,我还想将example.com/place/sta-ana/ 子目录中的所有文件重定向到example.com/place/santa-ana/$1

标签: regex apache .htaccess redirect mod-rewrite


【解决方案1】:

看起来您不需要RewriteCond。只需这条规则就可以了:

RewriteRule ^place/sta-ana(\.html|/.*)$ /place/santa-ana$1 [L,NC,R=301,NE]

确保这是您的最高规则,并且您必须在测试此更改之前完全清除浏览器缓存。

【讨论】:

  • 我从online article 看到了this 流程图,该流程图显示即使没有匹配项也已完成替换。但是对于RewriteCond,如果找不到匹配项,则会跳过替换,我认为这会更有效。请赐教。
  • 对不起,我已经在 mod_rewrite 上发布了数百个有效的答案,但我不确定 substitution is done even though there is no match 的效果如何。你有机会测试我的答案吗?不行吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-05
  • 1970-01-01
相关资源
最近更新 更多