Remove .php extension (explicitly written) for friendly URL

miquel picture miquel · Mar 22, 2012 · Viewed 9.2k times · Source

htaccess to remove the .php extension of my site's files.

RewriteEngine on
RewriteBase /
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.*)$ $1.php [L,QSA]

Now, if I go to my site

www.mysite.com/home

works fine, it redirects to home.php but the URL is still friendly.

But if I write this URL:

www.mysite.com/home.php

The home.php is served, and the URL is not friendly.

How can I avoid this behavior? I want that if the user writes www.mysite.com/home.php, the URL displayed in the URL bar be www.mysite.com/home

Answer

Bhavana picture Bhavana · Jun 18, 2012

Code

RewriteEngine On
RewriteBase /

# remove enter code here.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]