Enable Mod_rewrite Apache

The Apache web server is the most popular web server powering millions of websites worldwide. It is a highly flexible web server and its modular structure allows you to extend its functionalities through the use of modules. There are several modules that can be used to enable different functions like mod_header, mod_expires and mod_rewrite. In this post, we are going to discuss mod_rewrite and how to enable it on the Apache server.

Mod_rewrite is a very useful module that can allow you to write urls more cleanly. This module uses a rule based rewriting engine that can rewrite requested urls on the fly. It provides a powerful and flexible way to manipulate urls using unlimited rules. Moreover, the rewrite rules can be invoked inside the Apache configuration files or inside the .htaccess file.

For example, you can use mod_rewrite to redirect users from the older outdated pages to the latest pages. If these outdated pages are still in Google’s index, it can be very useful to use permanent redirect rules to get the latest pages indexed in their place. Similarly, you can use mod_rewrite to write cleaner urls that are easy to remember in place of complex urls. You can create more understandable urls also with the help of this module.

While the actual url may look like http://www.example.com/gp/itemBVINHI0Q/ref=as_li_st_tl?, with the help of mod_rewrite, it can be written as example.com/latest_and_best/specific_products/product_youre_looking_for/ Now, you can see that mod_rewrite allows you to write simplified and customized urls.

Before you can start writing the actual rewrites inside the .htaccess file, you will need to activate the mod_rewrite on your Apache server. It is very simple to activate the module and can be done with a single command:

sudo a2enmod rewrite

This will activate the module rewrite and if the module is already active, you will receive the update that the module is already active on your server. If you have just activated the module, you will need to restart the Apache server for the changes to apply.

sudo systemctl restart apache2

That’s all you have activated the rewrite module and now you can start rewriting urls in the .htaccess file. However, you will also need to enable the use of .htaccess file on your server before you can start rewriting urls. To do that, you will need to add a few lines of code to your Apache configuration file and restart the Apache server.

<VirtualHost *:80>
    <Directory /var/www/html>
        AllowOverride All
    . . .

Replace /var/www/html with your root directory and then create a .htaccess file inside the root directory. Now, you can start creating rewrite rules. However, in the first line of the rewrite rule, you need to enter the following code to let the server know that you want to enable rewriting for the current website.

RewriteEngine on

Suggested Reading