htaccess replace characters in query parameter

2019-07-22 15:17发布

I have a url like http://www.example.com/?product=test&retailer=test&site=test

In this instance (where product parameter is present) I remove &site=test but leave the rest of the url untouched.

If product parameter isn't present, e.g. http://www.example.com/?retailer=test&site=test

I remove &site=test and change ?retailer=test to /retailer/test so the full url would be http://www.example.com/retailer/test. I also only make this happen on the root domain.

I do this using these rules

# 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]

on the second rule when the url is rewritten to /reatiler/test there is the possibility for this to be /retailer/test+test in this instance I need to change it to /retailer/test-test could also be /retailer/test+test+test which would need to be /retailer/test-test-test

help on this would be much appreciated

1条回答
冷血范
2楼-- · 2019-07-22 15:43

You could use the N flag (more info here):

RewriteRule ^retailer/(.*)\+(.*)$ /retailer/$1-$2 [N,R=301]

Note that this is actually equivalent, since a redirect is involved here:

RewriteRule ^retailer/(.*)\+(.*)$ /retailer/$1-$2 [R=301,L]

So finally your htaccess should look like this

# 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]

RewriteRule ^retailer/(.*)\+(.*)$ /retailer/$1-$2 [R=301,L]
查看更多
登录 后发表回答