Remove file Extensions in URL Apache2

This article is written specifically for Apache php tags, however, I see no reason it wouldn't work for other languages.


Change Apache2 Config

You must change the apache2 configuration file to allow for .htaccess


Make a back up just in case:

sudo cp apache2.conf apache2.conf.old 

Use nano to edit the file:

sudo nano apache2.conf

While in the file hit Ctrl-W type AllowOveride, do this several times until you find the /var/www AllowOverride. Change the line to look like this:

Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted


Create .htaccess

Next we need to make our .htaccess file

cd /var/www/html
sudo nano .htaccess

Add the following code:

Options +FollowSymLinks -MultiViews
     # Turn mod_rewrite on
     RewriteEngine On
     RewriteBase /
     ## don't touch /forum URIs
     RewriteRule ^forums/ - [L,NC]
     ## hide .php extension snippet
     # To externally redirect /dir/foo.php to /dir/foo
     RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
     RewriteRule ^ %1 [R,L]
     # To internally forward /dir/foo to /dir/foo.php
     RewriteCond %{REQUEST_FILENAME} !-d
     RewriteCond %{REQUEST_FILENAME}.php -f
     RewriteRule ^(.*?)/?$ $1.php [L]


Set Permissions

Close the file then change ownership to the www-data user and group

sudo chown www-data:www-data .htaccess

Enable mod_rewrite

The final step is to enable mod_rewrite module in apache2 and restart apache2. It is typically enabled by default but you can do so:

sudo a2enmod rewrite
sudo service apache2 restart