【问题标题】:Redirect URLs that do not start with specific string不以特定字符串开头的重定向 URL
【发布时间】:2018-07-04 19:20:52
【问题描述】:

大家好,我正在尝试进行重定向工作,但我不断收到错误“重定向太多”... 我想重定向所有不以特定字符串开头的 URL,我写了这个和许多其他的但没有工作:

RewriteRule !^(?=string1)(?=string2)(?=string3)/(.*) / [R=301,L]

有什么问题吗? 谢谢

【问题讨论】:

  • 你应该把模式写成RewriteRule ^/(?!string1|string2|string3)(.*) / [R=301,L]。或^/(?!(?:string1|string2|string3)/).*
  • 感谢 Wiktor 的回复,它几乎可以完美运行,我不得不删除第一个“/”,但它在主页中循环重定向。我将其更改为这样以排除主页:RewriteRule ^(?!/|string1|string2|string3)(.*) / [R=301,L] 但它并没有真正起作用:/
  • 试试RewriteRule ^/(?!string1|string2|string3|$)(.*) / [R=301,L],或者,如果第一个/仍然有问题,RewriteRule ^(?!/string1|/string2|/string3|/$)(.*) / [R=301,L]
  • 这两种解决方案仍然无法使用 :(
  • 好吧,如果^(?!string1|string2|string3).*(匹配任何不以string1string2string3 开头的字符串)不起作用,您需要.htaccess 专家帮助。

标签: regex apache .htaccess redirect url-rewriting


【解决方案1】:

您需要在重定向中排除主页:

RewriteRule ^(?!string1|string2|string3|$) / [R=301,L]

但是,在您清除浏览器缓存之前,这将不起作用。当你这样做时,它会停止重定向太多次。

【讨论】:

  • 您好,感谢您的回复。我清除了缓存并尝试了您的代码,它不会在主页的循环中重定向,它不会重定向 url site.com/string1/mypage/,但它会重定向 url site.com/string2/mypage/ 和之后重定向,它附加查询字符串:site.com/string2/mypage/ => site.com/?var_name=mypage
  • @Websphere 此规则将以相同的方式处理这两个路径。您的 htaccess 文件中还有其他规则吗?
  • 你是对的,我不得不在我的 htaccess 文件的开头移动这个规则,一切都像一个魅力。非常感谢 :) 但是,即使是 404 错误也会被重定向,有没有办法排除不同类型的错误(404、503、...)?
  • @Websphere 可以为%{ENV:REDIRECT_STATUS}添加条件。
猜你喜欢
  • 1970-01-01
  • 2018-07-13
  • 2018-11-15
  • 1970-01-01
  • 2015-05-16
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多