问题
I'm trying to rewrite URLs with underscores in to dashes for a shopping site.
Product names currently have underscores for spaces. A typical URL is as follows:
http://test.local/category-name/product_name_a
My current .htaccess is as follows and successfully rewrites this to:
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]
However some products have consecutive underscores in them such as
http://test.local/category-name/product__name__b
or a mixture of the two such as:
http://test.local/category-name/product__name_a
I've tried and failed to get these to rewrite to:
http://test.local/category-name/product--name--b
http://test.local/category-name/product--name-a
Without breaking the existing rewrites. Any help much appreciated.
回答1:
Just tweak your regex in 2nd rule:
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]
来源:https://stackoverflow.com/questions/29143918/rewrite-single-and-consecutive-underscores-to-dashes