htaccess 干净的 urls &用 - 替换空格和 %20 [英] htaccess clean urls & replacing whitespaces and %20 with -
问题描述
我正在努力完成这项工作.目前我的 htaccess 包含以下代码:
I'm strugling to make this work. At the moment my htaccess contains the following code:
#Debugging - Error reporting
php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
#Commpression
<ifmodule mod_deflate.c="">
<filesmatch ".(js|css|html|png|jpg|jpeg|swf|bmp|gif|tiff|ico|eot|svg|ttf|woff|pdf)$"="">
SetOutputFilter DEFLATE
</filesmatch>
</ifmodule>
Options All -Indexes +FollowSymLinks -MultiViews
<IfModule mod_rewrite.c>
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /
#RewriteCond %{THE_REQUEST} (\s|%20)
RewriteRule ^([^\s%20]+)(?:\s|%20)+([^\s%20]+)((?:\s|%20)+.*)$ $1-$2$3 [N,DPI]
RewriteRule ^([^\s%20]+)(?:\s|%20)+(.*)$ /$1-$2 [L,R=301,DPI]
#RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^.*\.(png|jpg|bmp|gif|css|js)$ [NC]
RewriteRule ^([^/]+/?.+)$ /index.php?req=$1 [L,QSA]
</IfModule>
如果我尝试使用这个 url,除了 1 件事之外,一切都很好:
Everything works great except 1 thing if I try this url for example:
http://www.domain.com/ test/
浏览器将其翻译为:http://www.domain.com/%20test/一>基本上在域之后,如果路径以空格或 %20 开头,则失败.任何人都可以指出将删除起始空格的解决方案吗?
the browser translates it like to: http://www.domain.com/%20test/ basically after the domain if the path starts with a whitespace or a %20 it fails. can anyone please point to a solution where the starting spaces will be removed ?
更新
目标:
www.domain.com/ this is a test / hello there /
或
www.domain.com/ this is a test
到
www.domain.com/this-is-a-test/
或 www.domain.com/this-is-a-test/hello-there
推荐答案
我对两年多前编写的代码感到内疚 :P
I am guilty of writing that code more than 2 years back :P
这段代码可以大大简化:
That can be hugely simplified by this code:
# 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]
PS:必须补充一点,您需要修复这些 URL 的来源,因为获取这样的 URL 确实不正常.
PS: 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.
这篇关于htaccess 干净的 urls &用 - 替换空格和 %20的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!