Remove File Extension from URLs

So you want Pretty URLs?

You have a site with index.php or index.html files and you want to create friendly URLs. A simple script I have been working on now for a few years this file is a .htaccess file and must live in the root of your domain so for example

Just as an FYI for anyone using or editing this, if you do not know what this is then check out more about friendly URLs and the concept of mod rewrite before adding this. If you experience and 500 errors or anything like that please remove the script.

The Code

AddType text/x-component .htc
RewriteEngine On
RewriteBase /
# remove .php; use THE_REQUEST to prevent infinite loops
RewriteCond %{THE_REQUEST} ^GET\ (.*)\.php\ HTTP
RewriteRule (.*)\.php$ $1 [R=301]
# remove index
RewriteRule (.*)/index$ $1/ [R=301]
# remove slash if not directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /$
RewriteRule (.*)/ $1 [R=301]
# add .php to access file, but don't redirect
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteCond %{REQUEST_URI} !/$
RewriteRule (.*) $1\.php [L]

What it Does?

This handy script will remove all .php extensions creating lovely SEO and human friendly URLs for your static site, it will also not mess up any exisiting folders that you have live on your domain.

Questions, comments or amends please let me know here.

Leave a comment