【问题标题】:Rewrite single and consecutive underscores to dashes将单个和连续的下划线重写为破折号
【发布时间】:2015-03-19 20:02:43
【问题描述】:

我正在尝试将带有下划线的 URL 重写为购物网站的破折号。

产品名称当前使用下划线表示空格。一个典型的 URL 如下:

http://test.local/category-name/product_name_a

我目前的.htaccess如下,成功改写为:

http://test.local/category-name/product-name-a

RewriteEngine On
RewriteBase /

#Rewrite Underscores to dashes
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^_]*)_([^_]*)$ $1-$2 [L,R=302,NE]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^_]*)_+(.+)$ $1-$2 [L]

# Redirect to index.php & standard Opencart stuff
RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

但是有些产品中有连续的下划线,例如

http://test.local/category-name/product__name__b

或两者的混合,例如:

http://test.local/category-name/product__name_a

我已经尝试将这些重写为:

http://test.local/category-name/product--name--b

http://test.local/category-name/product--name-a

不破坏现有的重写。非常感谢任何帮助。

【问题讨论】:

    标签: apache .htaccess mod-rewrite opencart


    【解决方案1】:

    只需在第二条规则中调整您的正则表达式:

    RewriteEngine On
    RewriteBase /
    
    #Rewrite Underscores to dashes
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^_]*)_([^_]*)$ $1-$2 [L,R=302,NE]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^_]*)_(.+)$ $1-$2 [L]
    
    # Redirect to index.php & standard Opencart stuff
    RewriteRule ^sitemap\.xml$ index.php?route=feed/google_sitemap [L]
    
    RewriteRule ^googlebase\.xml$ index.php?route=feed/google_base [L]
    
    RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
    RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]
    

    【讨论】:

    • 由于此更改将是永久性的,使用 301 重定向会更好吗?并且可以通过将第一条规则编辑为: RewriteRule ^([^_]*)_([^_]*)$ $1-$2 [L,R=301,NE]
    • 是的,在该规则中将 302 替换为 301,因为一切正常。
    猜你喜欢
    • 2013-01-24
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 2013-04-29
    • 1970-01-01
    • 2011-02-14
    相关资源
    最近更新 更多