【问题标题】:RegEx matching for URL redirect in htaccess用于 htaccess 中 URL 重定向的正则表达式匹配
【发布时间】:2019-09-20 14:21:03
【问题描述】:

我有一些动态网址。如果我使用带有查询参数的 url,它会导致 404 页面。所以我想使用 htaccess 进行重定向。我尝试使用匹配的 url 模式正则表达式,但它没有重定向。

网址结构将是/detail/2019-12/news/news-title-12-2019.html?something,我需要将其重定向到/detail/2019-12/news/news-title-12-2019.html

我尝试过这样的事情,但它没有重定向;

RewriteCond %{QUERY_STRING} .
RewriteRule ^detail/\d{4}-\d{2}/news/(?=\S*['-])([a-zA-Z0-9'-]+\.html)\?\S*$ %{REQUEST_URI}? [NC,L,R=301]

我该如何解决这个问题?

【问题讨论】:

  • RewriteRule 仅匹配 URL 的路径组件,如果要检查或匹配查询字符串内容,则需要在 RewriteCond 中进行。

标签: regex .htaccess mod-rewrite url-redirection


【解决方案1】:

您的规则不起作用的原因是您在规则正则表达式中检查查询字符串?。 RewriteRule 的模式仅适用于 URL 路径。

以下内容应该适合你

RewriteCond %{QUERY_STRING} .
RewriteRule ^detail/\d{4}-\d{2}/news/ %{RRQUEST_URI}? [L,R=301]

确保清除浏览器缓存或使用其他浏览器进行测试。

【讨论】:

    【解决方案2】:

    This RegEx 可能会帮助您编写 RewriteRul:

    ^(.+\.html)(\?.+)$ 
    

    我不太确定,但您的代码可能如下所示:

    RewriteCond %{QUERY_STRING} .
    RewriteRule ^(.+\.html)(\?.+)$ http://domain_goes_here/$1 [NC,L,R=301]
    

    RewriteCond %{QUERY_STRING} .
    RewriteRule ^(.+\.html)(\?.+)$ http://domain_goes_here/$1 [NC,L,R=302]
    

    您可能还需要:

    • 重启apache
    • 删除浏览器缓存

    如果您希望为您的表达式添加边界,this RegEx 可能会帮助您这样做:

    ^(\/detail\/[0-9-]+\/news\/[a-z0-9-]+\.html)(\?.+)$
    

    代码:

    RewriteCond %{QUERY_STRING} .
    RewriteRule ^(\/detail\/[0-9-]+\/news\/[a-z0-9-]+\.html)(\?.+)$ http://domain_goes_here/$1 [NC,L,R=301]
    

    RewriteCond %{QUERY_STRING} .
    RewriteRule ^(\/detail\/[0-9-]+\/news\/[a-z0-9-]+\.html)(\?.+)$ http://domain_goes_here/$1 [NC,L,R=302]
    

    【讨论】:

    • 嗨,艾玛,谢谢。但我需要与上述格式匹配的 url。我在网站上还有一些其他 URL 需要维护参数。我只需要从匹配的 url 模式中删除查询字符串。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多