【问题标题】:Remove just one GET parameter from url and rewrite another if a certain GET param isn't present - htaccess如果某个 GET 参数不存在,则仅从 url 中删除一个 GET 参数并重写另一个 - htaccess
【发布时间】:2017-05-23 09:06:34
【问题描述】:

我正在尝试在 url 重写上设置一些非常具体的条件,但我很挣扎。

假设我有一个类似http://www.example.com/?product=test&retailer=test&site=test的网址

在这种情况下(存在product 参数),我只想删除&site=test,但不更改url 的其余部分。

如果product 参数不存在,例如http://www.example.com/?retailer=test&site=test

我仍然想删除&site=test 并将?retailer=test 更改为/retailer/test,因此完整的网址将是http://www.example.com/retailer/test。我也只希望这发生在根域上。甚至只是为了删除site参数也很挣扎......

我试过了:

RewriteCond %{QUERY_STRING} (?:^|&)sitechange=([^&]+) [NC]
RewriteRule ^$ ? [L,R=301]

但这会删除所有实例中的所有参数

也试过这个:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{QUERY_STRING}  (.*)?&?site=[^&]+&?(.*)?  [NC]
RewriteCond %{REQUEST_URI} /(.*)
RewriteRule .*  %3?%1%2? [R=301,L]

但这没有任何作用。发现很难理解这些重写规则。如果有人可以帮助我将不胜感激

【问题讨论】:

    标签: apache .htaccess mod-rewrite url-rewriting


    【解决方案1】:

    假设您的参数有时是 product 并且总是 retailersite(按此顺序),您的规则应如下所示

    # first condition
    RewriteCond %{HTTP_HOST} ^www\. [NC]
    RewriteCond %{QUERY_STRING} ^product=([^&\s]+)&retailer=([^&\s]+)&site=test$ [NC]
    RewriteRule ^$ /?product=%1&retailer=%2 [R=301,L]
    
    # second condition
    RewriteCond %{HTTP_HOST} ^www\. [NC]
    RewriteCond %{QUERY_STRING} ^retailer=([^&\s]+)&site=test$ [NC]
    RewriteRule ^$ /retailer/%1? [R=301,L]
    

    【讨论】:

    • 谢谢,我会给这个,但是是的,根域我的意思是只在 www.example.com/
    • @Neil 我在两个规则中都添加了所需的条件以仅匹配 www
    • 非常感谢这个工作。我真的知道这是另一个问题,但你会碰巧知道我如何在这个位的论点中将“+”更改为“-”,对吗? RewriteRule ^$ /retailer/%1? [R=301,L]
    • 您的意思是在retailer 参数中将+ 替换为-?假设您有例如 ?retailer=one+thing ?
    • 是的,没错,正在做一些调查,但又在挣扎。需要对这个重写的东西进行打击。 /retailer/one-thing 也是如此
    【解决方案2】:

    尝试使用以下规则我假设 index.php 作为处理程序并假设其他约束由您处理。

    RewriteCond %{QUERY_STRING} ^product=([^/]+)&retailer=([^/]+)&site=([^/]+)$
    RewriteRule ^ index.php?product=%1&retailer=%2 [R=301]
    
    RewriteCond %{QUERY_STRING} ^retailer=([^/]+)&site=([^/]+)
    RewriteRule ^ /retailer/%1? [R=301]
    

    【讨论】:

    • 非常感谢您的回复。第二条规则运作良好,但不幸的是第一条规则不起作用:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2013-02-09
    • 2014-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多