将单个和连续的下划线重写为破折号

时间:2015-03-19 11:55:26

标签: apache .htaccess mod-rewrite opencart

我正在尝试使用下划线重写带有破折号的网址。

产品名称目前有空格的下划线。典型的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

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

1 个答案:

答案 0 :(得分: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]