htaccess clean urls&用 - 替换空格和%20

时间:2013-09-21 17:03:56

标签: .htaccess

我很努力地做这项工作。目前我的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>

如果我尝试这个网址,那么一切都很有效,除了一件事:

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 个答案:

答案 0 :(得分:9)

我在两年多前编写该代码时感到内疚: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]

PS:必须补充一点,您还需要修复这些网址的来源,因为获取此类网址实际上并不正常。

答案 1 :(得分:0)

这很好用

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