Rewrite single and consecutive underscores to dashes

这一生的挚爱 提交于 2020-01-15 12:33:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!