How to remove %20 from url with .htaccess

南楼画角 提交于 2019-12-20 03:16:25

问题


how to remove %20,:,/,? and many more from url with .htaccess? im already try code from this post, but still not replace/redirect to new url .htaccess url rewrite and removing %20.

this my .htaccess code

    RewriteEngine On
RewriteBase /

# external redirect from actual URL to pretty one (remove query string)
RewriteCond %{THE_REQUEST} \s/+content\.php\?judul=([^\s&]+) [NC]
RewriteRule ^ %1? [R=302,L,NE]

# convert all space (%20) to hyphen
RewriteRule "^(\S*) +(\S* .*)$" $1-$2 [N,NE]
RewriteRule "^(\S*) (\S*)$" $1-$2 [L,R=302,NE]

# rewrite rule to call actual PHP handler
RewriteRule ^([^./]+)\.html$ content.php?judul=$1 [L,QSA,NC]

my link
http://localhost/web/content.php?judul=Fate/Apocrypha
http://localhost/web/content.php?judul=Isekai%20wa%20Smartphone%20to%20Tomo%20ni

i want "%20" and "/" replace with "-" like this one.
http://localhost/web/content.php?judul=Fate-Apocrypha/
http://localhost/web/content.php?judul=Isekai-wa-Smartphone-to-Tomo-ni/


回答1:


You can add these 2 rules before your last rewrite rule:

# replace %20 and / in QUERY_STRING by hyphen
RewriteCond %{QUERY_STRING} "^([^/]*?)(?:/|%20)+([^/]+?(?:/|%20)+.*)$"
RewriteRule ^ %{REQUEST_URI}?%1-%2 [N,NE]

RewriteCond %{QUERY_STRING} "^([^/]*?)(?:/|%20)+([^/]+?)/?$"
RewriteRule ^ %{REQUEST_URI}?%1-%2/ [L,R=302,NE]



回答2:


Use this code , hope it will help you.

# remove spaces from start or after /
RewriteRule ^(.*/|)[\s%20]+(.+)$ $1$2 [L]

# remove spaces from end or before /
RewriteRule ^(.+?)[\s%20]+(/.*|)$ $1$2 [L]

# replace spaces by - in between
RewriteRule ^([^\s%20]*)(?:\s|%20)+(.*)$ $1-$2 [L,R]

NOte- Must add that you need to fix the source of these URLs also because it is really not normal to be getting URLs like this.



来源:https://stackoverflow.com/questions/44733073/how-to-remove-20-from-url-with-htaccess

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