FREE THOUGHT · FREE SOFTWARE · FREE WORLD

Rewrite underscores to hyphens for SEO URL

This Apache .htaccess code 301 redirects requests for URLs with underscores (_) to the URL with hyphens.

Please see this article for the working updated code.

SEO benefits of using hyphens/dashes over underscores

According to Matt Cutts the choice is clearly to use dashes or hyphens instead of underscores.

So instead of article_this_is_awesome_page.html you want article-this-is-awesome-page.html.

I often get asked whether I'd recommend dashes or underscores for words in urls. For urls in Google, I would recommend using dashes.


Updated Htaccess

Thanks to lucus for supplying this improved version:

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} !\.(html|php)($|?) [NC]
RewriteRule ^([^_]*)_+(.*)$ $1-$2 [E=underscores:Yes,N]

RewriteCond %{ENV:underscores} ^Yes$
RewriteRule (.*) http://%{HTTP_HOST}/$1 [R=301,L]

Example Usage

When http://d.com/the_top_apache_htaccess_article.html is requested by a browser or search engine, a Search-Engine Friendly 301 Redirect is sent telling the client that the correct location for the resource is at http://d.com/the-top-apache-htaccess-article.html

The Apache .htaccess underscore to hyphen conversion code

Options +FollowSymLinks
RewriteEngine On
RewriteBase /

RewriteRule !\.(html|php)$ - [S=6]
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 (.*) https://www.askapache.com/$1 [R=301,L]

Further Reading

  1. The Worlds Greatest Apache .htaccess Guide
  2. Article in htaccessElite forum:Rewrite urls separated by _ underscores to - dashes

Htaccess

 

 

Comments