2

I want to replace all hyphens inside of an URL before permanent 301 redirection. For example this: http://www.example.com/article_category/article_name to this: http://www.example.com/article-category/article-name

My .htaccess file looks like this:

Options +FollowSymlinks
RewriteEngine On

RewriteCond %{REQUEST_URI} ![_]
RewriteRule .? - [S=2]
RewriteRule ^/?([^_]+)_(.*)$ $1-$2 [N,L]
RewriteRule ^(.*)$ /$1 [R=301,L]

[S] flag is there to prevent the last rule to repeat every time redirect occurs, causing loop. But it seems that the last rule isn't firing, because requested URL stays the same, while I get the content from wanted page. I tried removing L flag from the third line, but it causes loop :(

Joshua
  • 40,822
  • 8
  • 72
  • 132
geter712
  • 31
  • 3

1 Answers1

2

It may be easier to just use environment variables. You can set them using the E rewrite flag. Then you can check against the env variable in a rewrite cond:

Options +FollowSymlinks
RewriteEngine On

RewriteRule ^(.*)_(.*)$ /$1-$2 [E=DASH:Y,DPI]
RewriteCond %{ENV:DASH} Y
RewriteRule ^([^_]+)$ /$1 [L,R=301]

So the first rule checks to see if there is a _ in the URI, then rewrites it to a - instead. Because this rewrite happens, we set the DASH environment variable.

The second rule won't do anything unless the environment variable DASH is set, which means there is at least 1 _ rewritten to -, and the regex makes sure there are no more _ left in the URI before redirecting to browser.

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
  • Thanks for answer. Interesting approach with env var, but it still doesn't redirect. – geter712 Feb 19 '15 at 12:58
  • @geter712 weird, could have sworn it was working for me. So 2 things here, the ENV was missing with the `L` flag so I removed that, and also there's a [strange bug with apache](https://bz.apache.org/bugzilla/show_bug.cgi?id=38642) that may or may not be happening, which is why I added a `DPI` flag to drop the PATH_INFO. See the edits above – Jon Lin Feb 19 '15 at 23:00
  • Strange bug or not, it was eating my nerves for three days so I've decided to call external php script to put together url and do 301. Mod_rewrite is quite powerful but also very unnecessary complicated and buggy... – geter712 Feb 20 '15 at 16:27