apache - 如果某个 GET 参数不存在,则仅从 url 中删除一个 GET 参数并重写另一个 - htaccess

标签 apache .htaccess mod-rewrite url-rewriting

我正在尝试为 url 重写设置一些非常具体的条件,但我很吃力。

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

的 url

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

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

我仍然想删除 &site=test 并将 ?retailer=test 更改为 /retailer/test 所以完整的 url 将是 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]

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

最佳答案

假设您的参数有时是 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]

关于apache - 如果某个 GET 参数不存在,则仅从 url 中删除一个 GET 参数并重写另一个 - htaccess,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44130406/

相关文章:

regex - 将 URL 从 http ://example. com/blog/重写为 http ://blog. example.com/

angular - 使用 Angular 配置 Tomcat 8

php - 使用 .htaccess 和友好 url 的网站翻译

PHP 重定向用户并设置 403 header

linux - 使用 htaccess .. 所有 url 都必须使用 www 重定向到 https

linux - Apache Http 基本身份验证 - 禁止错误 403

linux - 更改默认端口后 Apache2 不工作

php - 使用 RewriteRule 发送 POST 数据

apache - 仅允许某些文件通过 .htaccess 查看

laravel - 在 laravel 5.2 中将 http 重定向到 https