How To Rewrite URLs with mod_rewrite for Apache on Ubuntu

Enabling mod_rewrite

First,Activate mod_rewrite.

sudo a2enmod rewrite

These changes required restart Apache.

sudo systemctl restart apache2

mod_rewrite is enabled. Next step,set up an .htaccess file to define rewrite rules for redirects.

Setting Up .htaccess

An .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.

Apache prohibits using an .htaccess file to apply rewrite rules, so first you need to allow changes to the file. Open the default Apache configuration file using nano or your favorite text editor.

sudo nano /etc/apache2/sites-available/000-default.conf

you will find a block starting on the first line. Inside of that block, add the following new block so your configuration file looks like the following. Make sure that all blocks are properly indented.

Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted

. . .

Save and close the file. To put these changes into effect, restart Apache.

create the .htaccess file in the web root.

sudo nano /var/www/html/.htaccess

Add this line at the top of the new file to activate the rewrite engine.

RewriteEngine on

Save the file and exit.

Enjoy!