【问题标题】:htaccess file - change underscores to hyphens for more than two words in urlhtaccess 文件 - 将 url 中两个以上单词的下划线更改为连字符
【发布时间】:2017-06-27 20:31:33
【问题描述】:

我正在尝试将我的网站的所有下划线更改为连字符。目前我已将此代码添加到 .htaccess 文件中。

RewriteBase /

RewriteRule !\.(html|php)$ - [S=6]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5-$6-$7 [E=underscores:Yes]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5-$6 [E=underscores:Yes]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5 [E=underscores:Yes]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4 [E=underscores:Yes]
RewriteRule ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3 [E=underscores:Yes]
RewriteRule ^([^_]*)_(.*)$ $1-$2 [E=underscores:Yes]

RewriteCond %{ENV:underscores} ^Yes$
RewriteRule (.*) http://www.askapache.com/$1 [R=301,L]

但是,它仅适用于网址,例如 www.abc.com/about_us 到 www.abc.com/about-us,不适用于包含两个以上单词的网址,例如 www.abc.com/about_us_what_do_you_mean

有人可以帮我解决这个问题吗?谢谢

【问题讨论】:

    标签: javascript php apache .htaccess mod-rewrite


    【解决方案1】:

    不用这么多复杂的规则,你可以使用这两个递归规则将所有下划线替换为连字符:

    RewriteEngine On
    
    RewriteRule \.(html?|php)$ - [L,NC]
    
    RewriteRule ^([^_]*)_+([^_]*)$ http://www.askapache.com/$1-$2 [L,R=301,NE]
    
    RewriteRule ^([^_]*)_+(.*)$ $1-$2 [N,DPI]
    

    【讨论】:

    • 感谢您的回答。但是,这会带来相同的问题,因为大名称的 Url 不会更改为连字符,例如 test.com/front/a_b_c_d。不过它适用于test.com/front/a_b
    • 适用于小 url,但现在对于较长的 url,它指向 askapache.com/a-b-c-d.... 并且在选项卡上找不到 404 页面。我尝试将 url askapache.com 更改为我的 url,但它仍然指向 askapache.com
    • 这是由于浏览器缓存造成的。彻底清除浏览器缓存并测试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-13
    • 1970-01-01
    相关资源
    最近更新 更多