【问题标题】:htaccess clean urls & replacing whitespaces and %20 with -htaccess clean urls & 用 - 替换空格和 %20
【发布时间】:2013-09-26 22:23:39
【问题描述】:

我正在努力完成这项工作。目前我的 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>

如果我尝试这个网址,除了 1 件事之外,一切都很好:

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

【问题讨论】:

    标签: regex apache .htaccess mod-rewrite


    【解决方案1】:

    我为两年多前编写该代码感到内疚: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:必须补充一点,您还需要修复这些网址的来源,因为获得这样的网址确实不正常。

    【讨论】:

    • 是的,我在 stackoverflow 中看到了您的答案中的代码。有没有办法完全删除任何起始空格?例如:www.domain.com/ 一个测试变成了 www.comin.com/-a-test。是否可以使其成为 www.domain.com/a-test ?
    • 感谢您提出这个问题,因为在较新的 Apache 版本中确实不需要 DPI 标志。
    • 还有 www.domain.com/ hello there/ 变成 www.domain.com/----hello-there//
    • 哦,所以你只是想删除起始空格?
    【解决方案2】:

    这很好用

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

    【讨论】:

      猜你喜欢
      • 2012-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-16
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      相关资源
      最近更新 更多