Removing Extensions
To remove the .php
extension from a PHP file for example yoursite.com/wallpaper.php
to yoursite.com/wallpaper
you have to add the following code inside the .htaccess
file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
If you want to remove the .html
extension from a html file for example yoursite.com/wallpaper.html
to yoursite.com/wallpaper
you simply have to change the last line from the code above, to match the filename:
RewriteRule ^([^\.]+)$ $1.html [NC,L]
That’s it! You can now link pages inside the HTML document without needing to add the extension of the page. For example:
<a href="http://whatever.com/wallpaper" title="wallpaper">wallpaper</a>
Adding a trailing slash at the end
I received many requests asking how to add a trailing slash at the end, for example: yoursite.com/page/
Ignore the first snippet and insert the code below. The first four lines deal with the removal of the extension and the following, with the addition of the trailing slash and redirecting.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+)/$ $1.php
RewriteRule ^([^/]+)/([^/]+)/$ /$1/$2.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/)$
RewriteRule (.*)$ /$1/ [R=301,L]
Link to the HTML or PHP file the same way as shown above. Don’t forget to change the code if you want it applied to an HTML file instead of PHP.
Some people asked how you can remove the extension from both HTML and PHP files. I don’t have a solution for that. But, you could just change the extension of your HTML file from .html
or .htm
to .php
and add the code for removing the .php
extension.