Remove .php / .html extension from URL slug

Was recently working on a project, not using a CMS like WordPress and Daniel was making fun of me for requiring “.php” in my URL.

Naturally, that could not go without a response.

Example of What I wanted to Do

Naturally, that could not go without a response.

https://defragged.org/somdirectory/somefile.php
                        


I wanted to remove the ".php" extension from the URL, so that it reads:

https://defragged.org/somdirectory/somefile
						


If this is you, then here is the quick and dirty on how to get this done.

How To Remove .PHP / .HTML from URL Slug

I am working on Apache and the latest version of Ubuntu, but it should be the same for most of the latest versions.

Because this is a test server, I wanted to do a global deployment so that I don't have to worry about it anymore. This saves me from having to remember to do this in each web directory via an .htaccess file.

Navigate to your apache config file, something like this:

# vim /etc/apache2/apache2.conf 
                        


Scroll to the bottom, and append this to your file:

<Directory /var/www/>
 <IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)/$ $1 [R,L]
  RewriteCond %{REQUEST_FILENAME}.php -f
  RewriteRule (.*) $1.php [L]
  RewriteCond %{REQUEST_FILENAME}.html -f
  RewriteRule (.*) $1.html [L]
 </IfModule>
</Directory>
						


Save the file, and restart the web server.



service apache2 restart
						


That should be it, clear your browser cache, and revisit the site. It should do the trick.



Posted in   Application_Tips   Troubleshooting   Apache     by trunc_team

Improve Your Websites Speed and Security