mod rewrite - replace underscores with hyphens
Posted by: kdwolski
Posted on: 2008-01-31 09:06:00
Hi,
For SEO purposes I would like to rewrite my URLs, overwriting underscores with hyphens, and then redirecting to the new URL.
Here's what I have so far:
Code:
Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteRule !\.(htm)$ - [S=5]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5-$6-$7 [E=underscores:Yes]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5-$6 [E=underscores:Yes]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4-$5 [E=underscores:Yes]
RewriteRule ^([^_]*)_([^_]*)_([^_]*)_(.*)$ $1-$2-$3-$4 [E=underscores:Yes]
RewriteRule ^([^_]*)_([^_]*)_(.*)$ $1-$2-$3 [E=underscores:Yes]
RewriteRule ^([^_]*)_(.*)$ $1-$2 [E=underscores:Yes]
RewriteCond %{ENV:underscores} ^Yes$
RewriteRule (.*) http://www.something.com/$1 [R=301,L]
This works fine for replacing underscores in the actual .htm filename, but it does not replace underscores in any present sub-directories. When the page redirects it will redirect to the root directory, blowing away any sub directories that were present:
Original:
http://something.com/sub_dir/another.../test_file.htm
Redirected to:
http://something.com/test-file.htm
Does anyone have a better mod rewrite code block that can handle this problem? Maybe someone knows how I can modify what I currently have to solve this?
Thanks so much for your help! I really appreciate it!