How to Rewrite URLs with mod_rewrite for Apache on Ubuntu 18.04



Apache’s mod_rewrite module lets you rewrite URLs in a cleaner fashion, translating human-readable paths into code-friendly query strings. It also lets you rewrite URLs based on conditions.

An .htaccess file lets you create and apply rewrite rules without accessing server configuration files. By placing the .htaccess file in the root of your web site, you can manage rewrites on a per-site or per-directory basis.

In this tutorial, you’ll enable mod_rewrite and use .htaccess files to create a basic URL redirection, and then explore a couple of advanced use cases.

Enabling mod_rewrite

In order for Apache to understand rewrite rules, we first need to activate mod_rewrite. It’s already installed, but it’s disabled on a default Apache installation. Use the a2enmod command to enable the module:

sudo a2enmod rewrite

This will activate the module or alert you that the module is already enabled. To put these changes into effect, restart Apache.

sudo systemctl restart apache2

mod_rewrite is now fully enabled. In the next step we will set up an .htaccess file that we’ll use 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.

Before you start using .htaccess files, you’ll need to set up and secure a few more settings.

By default, 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

Inside that file, 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.

<VirtualHost *:80>
    <Directory /var/www/html>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Require all granted

    . . .

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

sudo systemctl restart apache2

Now, create an .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.

You now have an operational .htaccess file which you can use to govern your web application’s routing rules.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.