htaccess 清除URL中的空格和将百分号 "%20" 替换为破折号 "-"

3
我正在努力让这个工作起来。目前我的htaccess文件包含以下代码:
#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,例如:
http://www.domain.com/ test/

浏览器将其翻译为:http://www.domain.com/%20test/。基本上,如果路径以空格或%20开头,则会失败。请问有没有人可以指出一个解决方案,使开头的空格被删除? 更新: 目标:
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

2个回答

10

我有罪,因为我写了那段代码已经超过2年了 :P

这段代码可以通过以下代码大大简化:

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

注: 必须指出,您还需要修复这些URL的源,因为获取类似这样的URL并不正常。


是的,我在stackoverflow上看到了你的答案中的那段代码。 有没有办法完全删除任何开头的空格? 例如:www.domain.com/ a test 变成 www.comain.com/-a-test。是否可能将其变为 www.domain.com/a-test? - 0x_Anakin
感谢您提出这个问题,因为在新的Apache版本中,DPI标志并不是真正需要的。 - anubhava
也就是说,www.domain.com/ hello there/ 变成了 www.domain.com/----hello-there// - 0x_Anakin
哦,所以你只想删除开头的空格? - anubhava

-1

这个运行良好

<IfModule pagespeed_module>
    ModPagespeed on
    ModPagespeedEnableFilters collapse_whitespace,remove_comments
</IfModule>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接