Add html extension to uri using htaccess file or Nginx

Written by
Date: 2012-05-09 11:30:00 00:00


If for some reason (read switching blogging platform) you need to add .html extension to uri/url you can do it with

Nginx

location / {
  # do nothing it the extension is already present
  if ($request_filename ~* ^.+.html$) {
    break;
  }
  # add .html if it was not present
  if (-e $request_filename.html) {
    rewrite ^/(.*)$ /$1.html permanent;
    break;
  }
}

Apache .htaccess

If you are using Apache, and have access to .htaccess file, add this there:

RewriteCond %{REQUEST_URI} !^.*\.html$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.html [L,R=301]