.htaccess在一个301重定向中将所有'+'转换为'-'

时间:2018-09-26 14:25:55

标签: .htaccess redirect

目标

我想替换所有URL的“ +”符号并将它们转换为“-”。 URL中可以包含任意数量的“ +”,并且可以包含任意数量的斜杠。我不想重写搜索页面。

示例

每个示例的第一行是原始URL。第二个是我想要我的301重定向URL。

https://domain.co.uk/used+cars
https://domain.co.uk/used-cars

https://domain.co.uk/accessories/car+accessories/ferrari+accessories
https://domain.co.uk/accessories/car-accessories/ferrari-accessories

https://domain.co.uk/accessories/car+repair+supplies/old+cars/even+older+cars
https://domain.co.uk/accessories/car-repair-supplies/old-cars/even-older-cars

到目前为止

此代码有效,但我可以从Firefox Dev Tools中看到它,并且实际上为遇到的每个“ +”都创建301重定向。可以在301重定向中完成此操作吗?

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(.*?)(?:,|\+)+(.+?)\sHTTP [NC]
RewriteCond %{REQUEST_URI} !^/search
RewriteRule ^ /%1-%2 [L,NE,R=301]

1 个答案:

答案 0 :(得分:1)

您可以使用以下2条规则将每个+替换为-

RewriteEngine On

# executes repeatedly as long as there are multiple + in URI
RewriteRule "^([^+]*)\+([^+]+\+.*)$" $1-$2 [N,DPI]

# executes when there is a single + in URI
RewriteRule "^([^+]*)\+([^+]*)$" /$1-$2 [L,R=301,NE]

确保在网站根目录.htaccess中将这些规则放在其他规则之前,并确保从新浏览器进行测试。