Mike Mike - 5 months ago 14
Apache Configuration Question

Proper way to remove file extensions

What is the proper way to have URLs without file extensions on an Apache web server? Currently I'm using this implementation in an .htaccess file

RewriteEngine on
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule !.*\.php$ %{REQUEST_FILENAME}.php [L]

However, some URLs have a trailing / while others don't and I'm not sure why. I'd prefer it with a trailing / but does it make a difference? Also, if enter 'about.php' how can I get it to go to 'about' instead? drexel.edu has the file structure I'm looking to replicate, but I'm not sure how they do it.

Also, how does this affect SEO? Will search engines count pages like 'about.php' and 'about' as two separate duplicate pages or do they know it's the same thing without me having to do anything extra?


You can use these two rules for effectively removing .php extension and taking care of SEO rankings:

RewriteEngine On

# To externally redirect /file.php to /file
RewriteCond %{THE_REQUEST} \s/+(.+?)\.php[\s?] [NC]
RewriteRule ^ /%1 [R=301,NE,L]

# To internally redirect /file OR file/ to /file.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.+?)/?$ $1.php [L]

Due to first 301 redirection search engines will not cache /file.php page and only /file will be cached in search results.