【问题标题】:mod_rewrite match from start of URImod_rewrite 从 URI 开始匹配
【发布时间】:2015-02-10 18:28:26
【问题描述】:

下午好, 我很难让我的 mod_rewrite 规则从 URI 的开头匹配。我已经浏览了手册,但我必须遗漏一些(可能很明显)语法巫术。请考虑以下几点:

RewriteCond %{REQUEST_URI}              ^/(.*)/(foo|bar)/(.*) 
RewriteRule ^(.*)/(.*)/(.*)/            destination.php?first=$1&second=$2&third=$3              [QSA,L]

如果第二个 URI 参数是 foo 或 bar,(例如 url.com/first/foo/third)这将成功重定向到目的地,并带有相关参数。

如果 foo 或 bar 出现在第三个参数中(例如 url.com/first/second/foo),我希望发生不同的重定向。但是,下面的规则被忽略了,上面的规则仍然优先

RewriteCond %{REQUEST_URI}              ^/(.*)/(something-else)/(.*) 
RewriteRule ^(.*)/(.*)/(.*)/            destination.php?first=$1&second=$2&third=$3              [QSA,L]

我想我一定错过了一种明显的方法来强制重写只从 URI 的开头匹配 - 我尝试在前面加上斜杠来尝试将其强制到根级别,但到目前为止没有任何乐趣。

任何帮助将不胜感激! 谢谢

编辑 事实证明,这是由于一个基本的 RegEx 错误,而不是我错误地假设匹配需要从 URI 的开头开始。我不会编辑标题,因为其他人可能会犯类似的错误。

【问题讨论】:

    标签: .htaccess mod-rewrite


    【解决方案1】:

    .* 太贪心了。试试这两条规则:

    RewriteRule ^([^/]+)/(foo|bar)/([^/]+)/?$ destination.php?first=$1&second=$2&third=$3 [QSA,L]
    
    RewriteRule ^([^/]+)/([^/]+)/(foo|bar)/?$ destination2.php?first=$1&second=$2&third=$3 [QSA,L]
    

    【讨论】:

    • 啊,我明白了!我没有想到 RegEx 也会翻转并吃掉 / 。太棒了,这就像一个魅力。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 2023-03-10
    相关资源
    最近更新 更多