remove unwanted characters from url using htaccess rewrite rule

僤鯓⒐⒋嵵緔 提交于 2019-12-12 05:16:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!