ank
ank

Reputation: 53

Replace all forward slashes with dashes

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

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

So https://stackoverflow.com/foo/bar/baz should redirect to https://stackoverflow.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.

Upvotes: 5

Views: 1615

Answers (1)

anubhava
anubhava

Reputation: 785128

You can use these 2 rules in your root .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

Upvotes: 5

Related Questions