Alex Scotton

App & Web Developer

Rewrite .html file extensions with htaccess

Posted by Alex Scotton on 29/6/2013

If you have a static site or are using a generator, you may find yourself with URLs that look like this:

Rewrite ugly .html file extensions to SEO & User Friendly URLs

There are a range of answers out there on rewrites that will let you visit blog.html whilst ommiting the file extension, however these still allow for direct access to blog.html and therefore 2 urls for the same page - which could lead to SEO issues. Instead you need a solution that will redirect from /blog.html to /blog too.

I managed to rectify it by writing a few rules into my .htaccess file, assisted by this post by Niall Flynn. A .htaccess file in your root directory allows you to 'ReWrite' and 'ReDirect' these URLs and is often the method employed by the large CMSes like WordPress etc. If you already have a .htaccess file present in your root directory (note: that on unix systems dot files are hidden by default), open it up and check it doesn't already contain a rule like:

RewriteEngine On

If it does, ensure these new rules do not conflict with the existing rules (drop a comment below and I will try and advise if you're stuck). Otherwise, if the file does not exist, go ahead and create the file with the following rules:

# This tag ensures the rewrite module is loaded
<IfModule mod_rewrite.c>
  # enable the rewrite engine
  RewriteEngine On
  # Set your root directory
  RewriteBase /

  # remove the .html extension
  RewriteCond %{THE_REQUEST} ^GET\ (.*)\.html\ HTTP
  RewriteRule (.*)\.html$ $1 [R=301]

  # remove index and reference the directory
  RewriteRule (.*)/index$ $1/ [R=301]

  # remove trailing slash if not a directory
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_URI} /$
  RewriteRule (.*)/ $1 [R=301]

  # forward request to html file, **but don't redirect (bot friendly)**
  RewriteCond %{REQUEST_FILENAME}.html -f
  RewriteCond %{REQUEST_URI} !/$
  RewriteRule (.*) $1\.html [L]
</IfModule>

Now, if all is well, any request for a html file will be redirected to a SEO friendly URL:

Succesfully rewritten URL

You can also check with this handy curl command:

$ curlHead example.com/blog.html
HTTP/1.1 301 Moved Permanently
Date: Sat, 29 Jun 2013 19:45:15 GMT
Server: Apache
Location: http://www.staging.alexscotton.com/blog
Content-Type: text/html; charset=iso-8859-1