使用htaccess重写规则从URL中删除不需要的字符

时间:2014-12-15 08:14:55

标签: php .htaccess mod-rewrite redirect url-rewriting

在我最近的项目中,重写规则工作正常,但问题是我无法从网址中删除不需要的字符。以下是htaccess代码: -

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]

输入是     find.php?source = Noida,Uttar Pradesh,India& destination = Gurgaon,Haryana,India

输出是:     http://domain.com/Noida%2C+Uttar+Pradesh%2C+India-to-Gurgaon%2C+Haryana%2C+India.html

我只想从网址中删除%2C和+,并希望将它们替换为此 - 以便输出网址为: -

http://domain.com/Noida-Uttar-Pradesh-India-to-Gurgaon-Haryana-India.html   

1 个答案:

答案 0 :(得分:0)

您可以在DOCUMENT_ROOT/.htaccess文件中使用此代码:

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]
相关问题