重写下划线为破折号

时间:2015-03-18 18:18:41

标签: apache .htaccess mod-rewrite url-rewriting opencart

我知道有很多关于重写下划线的现有问题和答案,但我似乎无法让它适用于这种特殊情况。

我正在将现有的网上商店转换为Opencart。出于某些奇怪的原因,旧商店在类别名称中使用破折号,但在产品中使用了下划线。所以现有的网址如下:

www.example.com/category-name/product_name

我想将这些改写为:

www.example.com/category-name/product-name

我到目前为止的.htaccess规则如下:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^_]*)_([^_]*_.*) $1-$2 [N]
RewriteRule ^([^_]*)_([^_]*)$ /$1-$2 [L,R=301]    

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]

第一部分重写下划线,第二部分重定向到index.php。虽然这可以很好地重写:

www.example.com/category-name/product_name

为:

www.example.com/category-name/product-name

当我输入如下网址时,它会完全崩溃apache:

www.example.com/category-name/product_name_with_more_underscores

感谢任何帮助或指示。

感谢。

1 个答案:

答案 0 :(得分:1)

这样做:

# executes when there is exactly 1 space in URI
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^_]*)_([^_]*)$ /$1-$2 [L,R=302,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^_]*)_+(.+)$ $1-$2 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !\.(ico|gif|jpg|jpeg|png|js|css)$ [NC]
RewriteRule ^(.*)$ index.php?_route_=$1 [L,QSA]
相关问题