问题
in my recent project, rewrite rule is working fine but problem is that i am not able to remove unwanted characters from the url. Below is the htaccess code :-
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^(www\.)?domain.com\.com$ [NC]
RewriteCond %{THE_REQUEST} /find\.php\?source=([^\s&]+)&destination=([^\s&]+) [NC]
RewriteRule ^ %1-to-%2.html? [R=302,L,NE]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\s]+)-to-([^\s]+)?.html$ find.php?source=$1&destination=$2 [L,QSA]
input is find.php?source=Noida, Uttar Pradesh, India&destination=Gurgaon, Haryana, India
and output is : http://domain.com/Noida%2C+Uttar+Pradesh%2C+India-to-Gurgaon%2C+Haryana%2C+India.html
I just want to remove %2C and + from url and want to replace them to this - so that output url will be :-
http://domain.com/Noida-Uttar-Pradesh-India-to-Gurgaon-Haryana-India.html
回答1:
You can use this code in your DOCUMENT_ROOT/.htaccess
file:
RewriteEngine On
RewriteBase /
# replace all comma by underscore
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.*?)(?:,|%2C)+(.+?)\sHTTP [NC]
RewriteRule ^ %1_%2 [L,NE,R=302]
# replace all space by hyphen
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.*?)(?:\+|%20|\s)+(.+?)\sHTTP [NC]
RewriteRule ^ %1-%2 [L,NE,R=302]
# redirect long URL to a pretty one
RewriteCond %{THE_REQUEST} /find\.php\?source=([^\s&]+)&destination=([^\s&]+) [NC]
RewriteRule ^ %1-to-%2.html? [R=302,L,NE]
# route pretty URL an actual one
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\s]+)-to-([^\s]+)?.html$ find.php?source=$1&destination=$2 [L,QSA]
来源:https://stackoverflow.com/questions/27479812/remove-unwanted-characters-from-url-using-htaccess-rewrite-rule