In this tutorial, we will show you how to manage URL rewrites using Apache2’s mod_rewrite module. When we installed a fresh Apache server mod_rewrite is not enabled by default on server, So to use rewrite configurations we need to manually enable mode_rewrite module on our system.This is a most basic way to enable mod_rewrite.
Enabling mod_rewrite
To enable mod_rewrite module in our Apache setup,we use following command:
a2enmod rewrite
And restart the Apache:
service apache2 restart
Setting Up .htaccess
Using .htaccess file we can modify our rewrite rules without accessing server configuration files. That’s why, .htaccess is critical for our web application’s security.
First, to allow changes in the .htaccess file. Open the default Apache configuration file using your favorite text editor.
nano /etc/apache2/sites-enabled/000-default.conf
Into that file, Search for “DocumentRoot /var/www/html” and add the following lines directly below:
<Directory /var/www/> Options Indexes FollowSymLinks AllowOverride All </Directory>
To put these changes into effect, restart Apache again.
service apache2 restart
Now create the .htaccess file:
nano /var/www/html/.htaccess
Add the following line at the top of newly created file to enable RewriteEngine.
RewriteEngine on
Save and exit the file.
To make sure that other users can only read your .htaccess , run the following command to update permissions:
chmod 644 /var/www/html/.htaccess
Now to check if mod_rewrite is installed correctly, check your phpinfo() output.