用破折号替换所有正斜杠

时间:2021-08-18 16:53:26

There are a few similar questions on SO, but none that work for this specific scenario.

在SO上有一些类似的问题,但没有一个适用于这个特定的场景。

I want to replace all forward slashes in a URL path with dashes, using mod_rewrite.

我想使用mod_rewrite用破折号替换URL路径中的所有正斜杠。

So https://*.com/foo/bar/baz should redirect to https://*.com/foo-bar-baz.

所以https://*.com/foo/bar/baz应该重定向到https://*.com/foo-bar-baz。

There could be any number of segments in the path (between forward slashes).

路径中可以有任意数量的段(正斜杠之间)。

I think the solution involves the N flag, but every attempt I've made results in an endless loop.

我认为解决方案涉及N标志,但我所做的每一次尝试都会产生无限循环。

1 个解决方案

#1


4  

You can use these 2 rules in your root .htaccess:

您可以在根目录中使用这两个规则.htaccess:

RewriteEngine On
RewriteBase /

RewriteRule ^([^/]+)/([^/]+)/?$ $1-$2 [NE,L,R=302]

RewriteRule ^([^/]+)/(.+)$ $1-$2

This will redirect example.com/foo/bar/baz/abc/xyz/123 to example.com/foo-bar-baz-abc-xyz-123

这会将example.com/foo/bar/baz/abc/xyz/123重定向到example.com/foo-bar-baz-abc-xyz-123

#1


4  

You can use these 2 rules in your root .htaccess:

您可以在根目录中使用这两个规则.htaccess:

RewriteEngine On
RewriteBase /

RewriteRule ^([^/]+)/([^/]+)/?$ $1-$2 [NE,L,R=302]

RewriteRule ^([^/]+)/(.+)$ $1-$2

This will redirect example.com/foo/bar/baz/abc/xyz/123 to example.com/foo-bar-baz-abc-xyz-123

这会将example.com/foo/bar/baz/abc/xyz/123重定向到example.com/foo-bar-baz-abc-xyz-123