Step1: Enabling mod_rewrite
Now, we need to activate mod_rewrite.
sudo a2enmod rewrite
This will activate the module or alert you that the module is already in effect. To put these changes into effect, restart Apache.
sudo service apache2 restart
Step2: Setting Up .htaccess
In this section, we will setup a .htaccess file for simpler rewrite rule management.
A .htaccess file allows us to modify our rewrite rules without accessing server configuration files. For this reason, .htaccess is critical to your web application's security. The period that precedes the filename ensures that the file is hidden.
We will need to set up and secure a few more settings before we can begin.
First, allow changes in the .htaccess file. Open the default Apache configuration file using nano or your favorite text editor.
sudo nano /etc/apache2/sites-enabled/000-default.conf
Inside that file, you will find the block on line 1. Inside of that block, add the following block:
/etc/apache2/sites-available/default
<Directory /var/www/html>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
</Directory>
Your file should now match the following. Make sure that all blocks are properly indented.
/etc/apache2/sites-available/default
<VirtualHost *:80>
<Directory /var/www/html>
. . .
</Directory>
. . .
</VirtualHost>
To put these changes into effect, restart Apache.
sudo service apache2 restart
Now, create the .htaccess file.
sudo nano /var/www/html/.htaccess
Add this first line at the top of the new file to activate the RewriteEngine.
/var/www/html/.htaccess
RewriteEngine on
Save and exit the file.
To ensure that other users may only read your .htaccess, run the following command to update permissions.
sudo chmod 644 /var/www/html/.htaccess
You now have an operational .htaccess file, to govern your web application's routing rules.