Remove .php extension from the URL [htaccess]

I love PHP, but my boss does not. Once, he was not happy to see the project coded in PHP by seeing the .php extension on the URL, citing the reason as it is an old language and many new languages like NodeJS have emerged which should’ve been used to code the project! Though all my explanation and convincing went in vain! I decided to remove .php extension from the URL. Of course, removing the .php extension does not really prevent people from knowing the language that was used to build an application. But if your boss is dumb just like many out there, then one solution was to hide. Said that, from a security perspective, it is good to do so. Other benefits of using an extension-less URL are as follows:

  • URLs look cleaner
  • They are easy to type
  • It’s easy to remember
  • Make URLs more SEO keyword friendly (Though no direct SEO benefit)
  • You can change the underlying technologies
  • Can hide technologies behind it as explained earlier.

To remove the file extension we need to make changes in the .htaccess file.

Update .htaccess file

Check your website’s root folder for the file “.htaccess”. If you don’t have one, create it.

Remove php extension

Add the following code to your .htaccess file and save it.

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

# To externally redirect /dir/foo.php to /dir/foo
RewriteCond %{REQUEST_METHOD} !POST
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=302,L,NE]

## To internally redirect /dir/foo to /dir/foo.php
RewriteCond %{REQUEST_FILENAME}.php -f [NC]
RewriteRule ^ %{REQUEST_URI}.php [L]

If you have an AJAX request to PHP files with the POST method, then the above code might have an issue and such requests stop working. To bypass POST requests, look for the line RewriteCond %{REQUEST_METHOD} !POST

How to exclude a specific file/URL from the .htaccess Rewrite Rule?

If you want to keep the extension to certain files as some of them might be getting data from POST methods and sometimes errors can occur while redirecting those pages. To exclude a file from removing the extension, just add the following line to your .htaccess code.

Exclude specific file/URL

RewriteCond %{REQUEST_URI} !^/file.php$

Exclude specific sub-directory

RewriteRule ^admin - [L]
Updated on November 11, 2021

Was this article helpful?

Related Articles

Leave a Comment