Remove .php Extension From URL Using htaccess
In certain situations, you might want to hide the extension of your files just to make your website a little more complex for hackers to hack. Or you might want to do hide the extensions for the sake of pretty URLs. Whatever maybe the reason, here is an easy way to hide the file extension using .htaccess.
How To Remove .php Extension From URLs Using .htaccess
There are just two steps involved. They are:
1. Simply copy and paste the following code in your .htaccess file, save & upload back to your server:
# Turn on the rewrite engine RewriteEngine On # Remove all .php extension from URL RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ $1.php
2. Strip off the .php extension from any hyperlinks that you may have in your webpage. For example, you may have a list of hyperlinks in your Header Navigation area that say: index.php, about.php, contact.php, ..etc. Simply remove the .php extension from those hyperlinks. Don’t worry, you will be able to navigate to the other pages even after you remove that extension provided you have not made any mistake while adding the code to .htaccess.
That’s it! That’s all you need to do hide the .php extension from URLs using .htaccess.
TIP:
Let’s say that you have a folder called “restricted” and you have some PHP files in this folder. Now you don’t want any of the php files in this folder to lose their extension i.e. whenever you view a page in this folder, the complete URL with the file extension should appear. So for example, you would like the page URL to appear like so:
http://www.mydomain.com/restricted/restrictedfile.php
When you place the code (shown in Step 1) in .htaccess file, when you access the restricted file via the URL, you would normally see the URL as: http://www.mydomain.com/restricted/restrictedfile but you want to see it as http://www.mydomain.com/restricted/restrictedfile.php. So to make this change, replace the existing code in .htaccess file with the following code:
# Turn on the rewrite engine RewriteEngine On # Ignore rewriting in /restricted folder - Change this to reflect to a folder of your choice RewriteCond %{REQUEST_URI} !^restricted/ # Remove all .php extension from URL RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ $1.php
Simple, isn’t it?
Do you know of any other ways to using .htaccess to remove .php extension from URLs? Feel free to suggest by commenting below.