如何使用.htaccess从url中删除%20

时间:2017-06-24 05:24:33

标签: php apache .htaccess mod-rewrite

如何删除%20,:,/,?还有更多来自.htaccess的网址? 我已经尝试过这篇文章的代码,但仍然没有替换/重定向到新的网址 .htaccess url rewrite and removing %20

这是我的.htaccess代码

    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]

我的链接
http://localhost/web/content.php?judul=Fate/Apocrypha
http://localhost/web/content.php?judul=Isekai%20wa%20Smartphone%20to%20Tomo%20ni

我希望“%20”和“/”替换为“ - ”,就像这样 http://localhost/web/content.php?judul=Fate-Apocrypha/
http://localhost/web/content.php?judul=Isekai-wa-Smartphone-to-Tomo-ni/

2 个答案:

答案 0 :(得分:0)

使用此代码,希望它能为您提供帮助。

# 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-必须补充一点,您还需要修复这些网址的来源,因为获取此类网址实际上并不正常。

答案 1 :(得分:0)

您可以在上次重写规则之前添加这两条规则:

# 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]