We help IT Professionals succeed at work.

How to rewrite url with dashes instead of underscores?

Mulith
Mulith used Ask the Experts™
on
Hi All,

I'm currently changing my URL structure but not sure how write my rule to do this.

This is the rule I want to use but also need it to substitute  underscores with dashes:

RewriteCond %{REQUEST_URI} !Franchise_Search_Results.php
RewriteRule ^Franchises/([^.]+)/([^.]+)\.php$ Franchises/$1/$2 [R=301,L]

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
kaufmedGlanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
Try introducing a new rule:

RewriteCond %{REQUEST_URI} !Franchise_Search_Results.php
RewriteRule ([^_]*)_(.*) $1-$2
RewriteRule ^Franchises/([^.]+)/([^.]+)\.php$ Franchises/$1/$2 [R=301,L]

Open in new window


I haven't tested, and it's been a while since I played around with Apache, but IIRC, the rewrite engine should continue to reprocess the incoming request until no more underscores remain; then the 301 rule will be processed. I may be missing a flag to invoke this behavior on that new rule, though.
Top Expert 2010
Commented:
Two issues with "kaufmed" post, first of the added rule is lacking an "N" (Next) flag, so won't currently recurse and replace and subsequent _ in the URL, see: http://httpd.apache.org/docs/current/rewrite/flags.html#flag_n 

Secondly the new rule has been inserted into the middle of the existing rule, thus breaking the both.

So, a quick hack and the following is probably closer to what you require:

RewriteRule ([^_]*)_(.*) $1-$2      [N]
RewriteCond %{REQUEST_URI} !Franchise-Search-Results.php
RewriteRule ^Franchises/([^.]+)/([^.]+)\.php$ Franchises/$1/$2 [R=301,L]

Open in new window


Note: have changed _Search_   to:  -Search-