yoast seo

Convert underscores to dashes with Apache mod_rewrite

Convert underscores to dashes with Apache mod_rewrite

March 25th, 2007 – 1 Comment

Update: (Aug 4 2007) the stuff below is no longer necessary, all major search engines now treat underscores and dashes exactly the same, as word separators!

Optimize your site for search & social media and keep it optimized with Yoast SEO Premium »

Yoast SEO for WordPress pluginBuy now » Info

A year or so back, I was using underscores in my URL’s on this site for spaces, and I decided to switch them to dashes, since several people, including Matt Cutts, had blogged that this was “the way to go”. Now at that time I just redirected all old URL’s to new ones, which created like 30 lines in my Apache config, something I didn’t really like…

This morning I took the time to find a more elegant solution, and the easiest one I could come up with is the following:

RewriteCond %{REQUEST_URI} ^(.*)_(.*)/$
RewriteRule (.*)_(.*)/ https://yoast.com$1-$2/ [R=301]

This will rewrite a single underscore to a single dash, using a 301 redirect. So if you have directories with four underscores, it will go through this rewrite four times before reaching the final URL. I had some directories in which this was the case, and made sure it only had to redirect a maximum of two times by adding the following lines above it:

RewriteCond %{REQUEST_URI} ^(.*)_(.*)_(.*)/$
RewriteRule (.*)_(.*)_(.*)/ https://yoast.com$1-$2-$3/ [R=301]

You could add even more lines like these if need be, I’d make sure that no more than two redirects are needed to rewrite the underscores into dashes.

The “/” on the end of the RewriteCond is there to make sure this is a directory, and not a file, since I’ve got quite a few images with underscores in the names and didn’t want to bother renaming them.

1 Response to Convert underscores to dashes with Apache mod_rewrite

  1. Gerben Coumou
    By Gerben Coumou on 28 March, 2007

    Sometimes an unnecessary variable makes some nasty URLs getting indexed.
    This could be, for example some session id or whatever.
    Use the following lines in your htaccess-file to get this fixed:

    RewriteCond %{QUERY_STRING} ^sessionId=
    RewriteRule ^(.*) http: //yoast.com/$1? [R=301]

Check out our must read articles about Analytics