Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 551
ank Avatar asked Mar 13 '15 01:03

ank


People also ask

What function could you use to replace slashes for dashes in a list?

If your dates are formatted with forward slashes (/), you are going to enter a forward slash into BOTH the Find what and Replace with fields. If your dates are formatted with dashes (-), then use dashes. Then click Replace All. (The keyboard shortcut for Replace All is Alt + A .)

How do I change the forward slash in regex?

To replace all forward slashes in a string:Call the replace() method, passing it a regular expression that matches all forward slashes as the first parameter and the replacement string as the second. The replace method will return a new string with all forward slashes replaced.

How do you change the backslash on a forward slash?

Press \/ to change every backslash to a forward slash, in the current line. Press \\ to change every forward slash to a backslash, in the current line.

What is the difference between forward slashes and backslashes?

Summary: The Backslash and Forward Slash Make sure to remember the following: The backslash (\) is mostly used in computing and isn't a punctuation mark. The forward slash (/) can be used in place of “or” in less formal writing. It's also used to write dates, fractions, abbreviations, and URLs.


1 Answers

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

like image 117
anubhava Avatar answered Oct 11 '22 09:10

anubhava