Removing whitespaces or %20 in url using htaccess

∥☆過路亽.° 提交于 2019-12-25 01:33:25

问题


hi guys can you help me here im having a little trouble here im tring to use the htaccess to remove all 20% in my url and replacing it with hyphen I manage to get rid the other 20% in between the words Acer,Liquid,S1,S510

here is my url /localhost/gadgets/product/Acer-Liquid-S1-S510%20Mobile

As you can see there is one %20 in last part, how can I remove it

And here is my htaccess

Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteBase /gadgets/

Options -Indexes

RewriteRule ^brand/([a-zA-Z]+)$ brand.php?id=$1

RewriteRule ^product/([A-Za-z0-9-]+)/?$   product.php?product_name=$1-$2 [NC,L]

RewriteRule ^(.*/|)[\s%20]+(.+)$ $1$2 [L]

RewriteRule ^(.+?)[\s%20]+(/.*|)$ $1$2 [L]

RewriteRule ^([^\s%20]*)(?:\s|%20)+(.*)$ $1-$2 [L,R]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f

RewriteRule ^(.*)$ $1.php

Thanks in advance guys


回答1:


Try this:

Options +FollowSymLinks -MultiViews -Indexes

RewriteEngine On
RewriteBase /gadgets/

RewriteRule ^([^\s%20]*)(?:\s|%20)+(.*)$ $1-$2 [N,E=Redirect:1]

RewriteCond {ENV:Redirect} ^1$
RewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [R,L]

RewriteRule ^brand/([a-zA-Z]+)$ brand.php?id=$1 [NC,L]
RewriteRule ^product/([A-Za-z0-9-]+)/?$ product.php?product_name=$1 [NC,L]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

The first rule removes all the whitespaces in a loop (using [N]) so we don't have to specify multiple RewriteRules doing it one by one now.

The next rule (with {ENV:Redirect} condition) is optional and is used to reflect the use of hyphens on the client's browser as well so that any bookmarks created link to the correct non-whitespaced version of the URL.



来源:https://stackoverflow.com/questions/28849327/removing-whitespaces-or-20-in-url-using-htaccess

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