If in htaccess for 301 Redirect special characters

2019-07-24 04:56发布

问题:

Rule: Redirecting all URLs that contains %252C+ to ,- and redirecting + to - only if the + comes with %252C+.

e.g1: http://www.example.com/FortWorth%252C+TX/ to: http://www.example.com/FortWorth,-TX/

e.g2: http://www.example.com/Fort+Worth%252C+TX/ to: http://www.example.com/Fort-Worth,-TX/

e.g3: http://www.example.com/Fort+Worth/ to: http://www.example.com/Fort+Worth/ (Should not redirect this one)

Note: Please remember your code should not be only for the above URL but for all URLs with the above rule.

回答1:

Thanks Sumurai8 , for your solution but it needs to be modified like This code :

RewriteEngine On

RewriteRule ^([^+]+)\+(.+)%2C+\+(.*)$ /$1-$2,-$3 [R,L]
RewriteRule ^([^+]+)%2C+\+(.*)$ /$1,-$2 [R,L]


回答2:

The first argument of RewriteRule is matched against the %-decoded url, so it should be matched against http://www.example.com/FortWorth%2C+TX/ for example instead of http://www.example.com/FortWorth%252C+TX/.

Assuming the strange substring only occurs once, and the "+" only appears once before that, you can do it with the following two rules. If multiple +'s can occur, things start to turn ugly quickly, because you'll need to either add a lot more rules, or start handling it recursively.

RewriteRule ^([^+]+)\+(.+)%2C\+(.*)$ $1-$2,-$3 [R,L]
RewriteRule ^([^+]+)%2C\+(.*)$ $1,-$2 [R,L]

I am not sure if mod_rewrite will escape the , character as a "special character". It is a valid character to use in an url. If it gives you problems, you could use the [NE] flag to prevent escaping such characters.