Oct 10, 2023 7 min read

How to Configure mod_rewrite

Configure mod_rewrite with our step-by-step tutorial. The mod_rewrite module is an Apache engine that rewrites URLs using rules.

Configure mod_rewrite
Table of Contents

Introduction

Before we begin talking about how to configure mod_rewrite, let's briefly understand – What is mod_rewrite?

The mod_rewrite module is an Apache engine that rewrites URLs using rules. The rules allow for the creation of various queries to convert URLs into the required format. Several applications include page redirection or proxy fetching.

In this tutorial, you will configure mod_rewrite. We will also address a few FAQs on how to configure mod_rewrite.

Prerequisites

  • Installed, set up, and operating (running) Apache web server.
  • An account with sudo access.
  • Access to a command-line tool or terminal.
  • Access to the installed curl command or a web browser.
💡
Note: A small Bare Metal Cloud (BMC) server is a cost-effective and reliable way to set up a testing environment. For instructions on setting up a development sandbox environment on a small BMC instance, see our use-case article. The small BMC instance costs as little as $0.08 per hour!

What Is mod_rewrite in Apache?

The Apache mod_rewrite module aids in server-side URL request manipulation. Patterns and rules c heck an inputted URL using regular expressions and variables to obtain information and serve the preferred page.

For instance, if the format of the requested URL is as follows:

example.com/foo/bar

The mod_rewrite module assists in converting the URL into a format that the server can process:

example.com/foo.php?id=bar

Accepting the first format has the following advantages:

  • From the user's point of view, the URL is less complex, more memorable, and simpler to replicate.
  • The first URL format provides semantic meaning to search engines.
  • From a security standpoint, it is critical that a user is ignorant that the first URL points to a file that contains the foo.php page.

A URL cannot be prettified by the mod_rewrite module. Instead, it converts pretty links into HTTP requests that the server can process.

How to use mod_rewrite?

The mod_rewrite module needs Apache to:

  • Activating the module.
  • Setting up the server.
  • Establishing the.htaccess file.

mod_rewrite and URL rewriting setting is a simple two-step procedure.

Enable mod_rewrite

Run the following commands in the terminal to enable mod_rewrite:

sudo a2enmod rewrite

The command prints a message indicating if the module is enabled or active. To apply the modifications, restart the Apache service:

sudo systemctl apache2 restart

The updated configuration is currently active.

Configure .htaccess to Override Website Configs

Without modifying the configuration files, the .htaccess file changes the website's details. Because it has an impact on all other files in the current directory and its subdirectories, save the file properly.

The sample project is located in the directory /var/www/html/.

1) Make the .htaccess file in the directory for the website:

sudo touch /var/www/html/.htaccess

.htaccess should then be set up to override website configuration:

2) Access the apache2.conf file:

sudo nano /etc/apache2/apache2.conf

You need sudo privileges to make modifications.

3) Find the following section:

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

The AllowOverride option should be changed from None to All:

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

Save the file and exit (CTRL + X, Y, Enter).

4) Start the Apache service once more:

sudo systemctl apache2 restart

Now, URL rewrites are possible since the .htaccess file supersedes all other settings.

mod_rewrite Directives

The .htaccess file is where the URL rewriting operations take place and contains a number of directives. Many of the instructions that are available are:

1) The engine that enables or disables the runtime is RewriteEngine. As for the syntax:

RewriteEngine On|Off

The RewriteEngine is not turned on by default. By turning the directive on or off, you can regulate runtime processing.

2) The RewriteCond directive keeps track of the circumstances in which rewrites take place. Its syntax is as follows:

RewriteCond TestString ConditionPattern [Flags]
  • The directive keyword for a single condition is RewriteCond. Several condition directives are conceivable before a single rule.
  • TestString includes server variables and backreferences in addition to plain text.
  • The TestString is subject to ConditionPattern, a Pearl Compatible Regular Expression (PCRE).

3) The rewriting engine follows the RewriteRule rules. The syntax is as follows:

RewriteRule Pattern Substitution [Flags]
  • The directive keyword for a single rule instance is RewriteRule. Order plays a key role, and there are multiple possible rules.
  • Pattern is a regex pattern used to match a specific section of a URL request. The Pearl Compatible Regular Expression (PCRE) syntax is used by the mod_rewrite module.
  • The actual URL of the data we wish to display is Substitution.
  • An optional parameter that modifies the behaviour of the expression is [Flags].

4) The mapping function for a key lookup is called RewriteMap. As for the syntax:

RewriteMap MapName MapType:MapSource [MapTypeOptions]
  • The mapping function's directive keyword is RewriteMap.
  • The function's name and the way to refer to it in a RewriteRule are both MapName.
  • The MapSource's file type is indicated by MapType. Also reliant on the MapType are the MapTypeOptions.
  • The path to the file holding the mapping data is called MapSource.

URL Rewrite Examples

Using real-world use cases is the most effective way to comprehend mod_rewrite directives. Here are a few such instances that show how mod_rewrite functions.

Write Contents of One Page on Another Page

When a page is requested, the contents of another page are served, which is a simple example of a URL rewrite. This use case applies when we wish to add fresh content to an existing page without changing the URL.

The .htaccess file appears as follows:

RewriteEngine On
RewriteRule ^old.html$ new.html [NC]
  • Line 1 activates the rewrite engine.
  • Line 2 includes the RewriteRule directive:
    1. The page that begins (^) and ends ($) with old.html matches the pattern ^old.html$.
    2. The new.html page is used as a replacement.
    3. The pattern is not case-sensitive, as indicated by the flag [NC].

The server displays the contents of the new.html page when a user tries to visit the old page.

Backreferencing RewriteRule Parameters

For a person accessing a URL with the following format:

http://example.com/product/foo/bar

The format of the rewritten URL request is as follows:

http://example.com/request.php?id=foo&name=bar

The following is the content of the .httaccess URL rewrite:

RewriteEngine On
RewriteRule ^product/([A-Za-z]+)/([A-Za-z]+)$ request.php?id=$1&name=$2

The parenthesis pattern is extracted by the rewrite algorithm and stored in the reference variables. The range of reference parameters is $1 to $9.

RewriteCondition Directive

RewriteRules are constrained by the RewriteCondition directive. To put it another way, the condition specifies the RewriteRule under which circumstances to apply the rewrite.

A broad constraint is provided by the condition. For instance, the rewrite aids in redirecting all requests ending in .html to .php if all web page extensions are switched from HTML to PHP.

Here is how the .htaccess file appears:

RewriteEngine On
RewriteCond %{HTTP_HOST} !php$
RewriteRule "^(.*).html$" "$1.php"

RewriteCond includes:

  • The test string is %{HTTP_HOST}. It is specifically a server variable that contains the entire HTTP host.
  • The condition pattern !php$ searches for any queries that don't end in .php.

Only when the RewriteCondition evaluates to true does the RewriteRule take effect. It now reads:

  • The match for the pattern is "^(.*).html$". The rewriting pattern precisely searches for requests with any initial characters and a .html ending.
  • The replacement is "$1.php". The $1 appends .php at the end and backreferences the string that comes before.html ((.*)).

RewriteCond facilitates swift migration by enabling an immediate redirect from outdated pages or domains to new ones.

RewriteEngine Directive

Every .htaccess file starts with the RewriteEngine directive, which may be turned on and off to regulate whether or not rewrites are performed. The functionality is useful for testing and debugging.

The RewriteEngine can also be used to "comment" portions of the .htaccess file. For instance:

RewriteEngine On
RewriteCond %{HTTP_HOST} !php$
RewriteRule "^(.*).html$" "$1.php"
RewriteEngine Off
RewriteRule ^old.html$ new.html [NC]
RewriteEngine On
RewriteRule ^product/([A-Za-z]+)/([A-Za-z]+)$ request.php?id=$1&name=$2

When the RewriteEngine is turned off for rules and conditions, mod rewrite waits until the engine is turned back on before executing the rewrite rules.

RewriteMap Directive

RewriteMap is a directive that improves rule substitution strings. This is an illustration of a form URL:

http://example.com/product/database

The rewrite prerequisite is:

http://example.com/products.php?id=272

Use RewriteMap and provide a file with key-value pairs containing the product names and IDs instead of manually looking it up.

An example of mapping from a file.txt with key-value pairs is shown below:

database 272
server 273
cloud 274

The rewrite file appears as follows:

RewriteEngine On
RewriteMap prodID "txt:/path/to/file.txt"
RewriteRule "^product/(.*)" "products.php?id=${prodID:$1}"

The file is organised as follows:

  • The file with key-value pairs is called file.txt. The data is used as a guide by Rewrite Map.
  • The map's name is prodID. In the rewrite rule substitution, the name makes it easier to refer to the function.
  • The string in the product name (database, server, cloud) or the URL is (.*). The value is used by the map function to look up the relevant ID in the file.txt.
  • ${profID:$1} returns the ID from the file after mapping the product name to an ID.

Many map types are available with the RewriteMap directive. For instance, the databases map type (dbd or fastdbd) employs a SELECT statement to retrieve data, but the randomised plain text map type (rnd) aids in the creation of load balancing solutions.

FAQs to configure mod_rewrite

How do I enable mod_rewrite? 

To enable mod_rewrite, run the command: sudo a2enmod rewrite and then restart Apache with: sudo service apache2 restart

Where is the configuration file for mod_rewrite located? 

The configuration file for mod_rewrite is typically located in the Apache configuration directory and named .htaccess.

How can I redirect a URL using mod_rewrite? 

To redirect a URL, add the following line to your .htaccess file: RewriteRule ^old-url$ /new-url [R=301,L]

Can I rewrite URLs to hide file extensions using mod_rewrite? 

Yes, you can achieve this by using the following rule in your .htaccess file: RewriteRule ^(.*)$ $1.php [L]

How can I redirect all HTTP requests to HTTPS using mod_rewrite? 

Add this rule to your .htaccess file: RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

How can I rewrite dynamic URLs to make them appear static using mod_rewrite? 

You can rewrite dynamic URLs with this rule: RewriteRule ^product/([0-9]+)/?$ product.php?id=$1 [L]

Can I block access to specific files or directories with mod_rewrite?

Yes, you can block access using this rule: RewriteRule ^private-directory/ - [F]

Conclusion

After going through the instructions and examples in this tutorial, you should be able to activate and use mod_rewrite. The examples demonstrate how to apply the mod_rewrite module to basic rewriting issues.

If you have any suggestions or queries, kindly leave them in the comments section.

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to DevOps Tutorials - VegaStack.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.