Step 1: Enable mod_rewrite
sudo a2enmod rewrite
You must restart Apache once you make any change to its configuration. To do this, type the command below on a terminal window:
sudo systemctl restart apache2
Your server is now ready to accept rewrite rules.
Step 2: Setup your server to accept .htaccess files
By default, Apache does not allow the use of ‘.htaccess’ file so you will need to edit the configuration of each website’s virtual host file by adding the following code:
<Directory /var/www/html> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory>
For instance, you can edit the default virtual hosts that ships with Apache using a nano editor by typing the command below:
sudo nano /etc/apache2/sites-available/000-default.conf
Then, restart Apache for the changes to take effect:
sudo systemctl restart apache2
Step 3: Mod-rewrite syntax
The basic Apache mod_rewrite syntax has the following parts:
RewriteRule pattern substitution [flags]
RewriteRule – the directive of our rule.
Pattern – this is a regex (Regular Expression) that matches what the user types in a browser.
Substitution – The actual URL path that should be called by the Apache server.
Flag – optional parameters that modify how the rules work..
Step 4: Create a sample .htaccess file
sudo nano /var/www/html/.htaccess
Every mod_rewrite rules must be with the commands ‘RewriteEngine on’. So you need to type this at the top of the file.
RewriteEngine on
Next, we are going to rewrite a rule that redirects users to a ‘contact_us.html’ page if they request the URL http://ipaddress/contact_us
So we add the below rule:
RewriteRule ^contact_us$ contact_us.html [NC]
So our complete ‘.htaccess’ a file should look like the text below:
RewriteEngine on RewriteRule ^contact_us$ contact_us.html [NC]