Apache - Enable .htaccess file

By xngo on November 26, 2019

By default, Apache doesn't execute .htaccess file. Therefore, Rewrite rules inside it are not triggered. Here are ways to enable it.

Change virtual host configuration file

The easiest way is to directly change the virtual host configuration file 000-default.conf. Add the following codes inside the <VirtualHost *:80> section of /etc/apache2/sites-available/000-default.conf.

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

Then, restart Apache server.

systemctl restart apache2

Create your own virtual host configuration file

It is recommended to create your own virtual host configuration file instead of directly changing the default file. As a result, your changes will not be overwritten if there is an upgrade.

All virtual host configuration file are stored in /etc/apache2/sites-available/ directory.

Here is how to create your own virtual host configuration file. Create /etc/apache2/sites-available/555-enable-htaccess.conf with the following settings:

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

Now that your configuration file is created with your own settings, you need to activate it. The easiest way to enable the virtual host is by using the a2ensite helper:

a2ensite 555-enable-htaccess

Or, the other option is to manually create a symlink as shown below:

ln -s /etc/apache2/sites-available/555-enable-htaccess.conf /etc/apache2/sites-enabled/

Once done, test the configuration for any syntax errors with:

apachectl configtest

You should expect the return message to be "Syntax OK".

Test rewrite rule

Test a simple rewrite rule to redirect a.html to bbbb.html. Create /var/www/html/.htaccess with the following rule:

RewriteEngine on
RewriteRule ^a.html$ /bbbb.html [NE,R]

Now, restart Apache server for the changes to take effect:

systemctl restart apache2

Open http://localhost/a.html with your browser. It will automatically redirect to http://localhost/bbbb.html.

Apache - Rewrite - Redirect from a.html to bbbb.html

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.