How to Set Up and Configure mod_rewrite with 5 Practical Examples

Try this guide with our instant dedicated server for as low as 40 Euros

mod rewrite

Whether you are a system administrator, a web developer, or even an SEO specialist, optimizing websites to improve user experience and SEO occupies a big part of your responsibilities.

So, have you ever wished you could transform clunky URLs into clean, user-friendly ones? Or maybe streamline redirects for a seamless website experience?

Apache provides mod_rewrite, a feature-rich module that simplifies the process and mechanism of modifying the URL of the hosted web apps.

The mod_rewrite module is a powerful tool that you can use for URL management, including complex URL rewriting and redirection requirements.

In this tutorial, we will discuss mod rewrite, how to set it up, and five practical examples of using the module for URl management and modification.

Table of Contents

  1. What is mod_rewrite in Apache?
  2. The Key Features of mod_rewrite
    1. URL Rewriting
    2. Redirection
    3. Access Control
    4. Proxying
    5. SEO Optimization
  3. The Prerequisites
  4. How to Use mod_rewrite?
    1. Step #1: Enable mod_rewrite
    2. Step #2: Configure .htaccess to Override Website Config
    3. Step #3: mod_rewrite Directives
  5. Test mod_rewrite Functionality
  6. URL Rewrite Examples
    1. Example #1: Redirect From One Page to Another
    2. Example #2: Backreferencing RewriteRule Parameters
    3. Example #3: RewriteCondition Directive
    4. Example #4: RewriteEngine Directive
    5. Example #5: RewriteMap Directive
  7. Conclusion
  8. FAQs

What is mod_rewrite in Apache?

Apache mod_Rewrite is a module for the Apache HTTP Server that provides URL manipulation capability.

It is primarily used for URL management, including complex URL rewriting and redirection to optimize websites effectively.

It allows administrators to modify URL requests on the server using rules and patterns, which can include regular expressions and variables. The modification process analyzes the URL and sets up redirection of all traffic landing at a specific URL to the appropriate page.

For instance, if a requested URL is in the following format:

example.com/foo/bar

The mod_rewrite module translates URLs into a format that the server can understand and process:

example.com/foo.php?id=bar

Here, the mod_rewrite module translates URLs into a format that’s:

  • Simple and memorable
  • Enhance the user experience by being more readable and intuitive.
  • Search engines can better interpret the URL, improving the website’s SEO ranking.
  • Includes relevant keywords, making it more SEO-friendly.
  • Users cannot see the underlying file structure (foo.php), which can help obscure the details of the server’s configuration and reduce the risk of targeted attacks.
  • Translates user-friendly URLs into HTTP requests that the server can comprehend and handle.

The Key Features of mod_rewrite

Let us now explore the key features that make mod_rewrite a great option for URl management.

URL Rewriting

mod_rewrite converts complex URLs with query strings into clean and more readable URLs. It enables dynamic URL structures without changing the underlying file and directory layout on the server.

Redirection

mod_rewrite implements permanent 301 Redirects to guide users and search engines to the new URL of a moved page. Similarly, you can implement temporary 302 redirects for pages that are temporarily unavailable.

Access Control

Based on various conditions, mod_rewrite restricts access to specific files or directories. It uses various parameters such as IP address, browser type, or the referring page to redirect users to specific web pages.

Proxying

mod_rewrite retrieves and displays content from another server or domain, acting as a reverse proxy component within the Apache server.

SEO Optimization

mod_rewrite creates SEO-friendly URLs that are easier for search engines to index and rank. It also prevents duplicate content issues by directing multiple URL versions to a single canonical URL.

Now that you have a basic understanding of mod_rewrite, let us see how to enable and configure mod_rewrite. However, before that, let us now take a quick look at the prerequisites.

The Prerequisites

Before diving into the setup and configuration, ensure you have the following:

  • Access to an Apache web server
  • A user account with sudo or administrative privileges
  • Access to the terminal/command line.

How to Use mod_rewrite?

mod_rewrite allows users to transform URLs for the apps hosted on your Apache server, enhancing user experience, SEO, and content organization. But before you can get these benefits, you need to enable the module.

So, here are the main steps in working with mod_rewrite.

Step #1: Enable mod_rewrite

mod_rewrite, by default, is installed but disabled on an Apache installation. In order to configure the Apache web server and enable the module, follow these steps:

Open your terminal and execute the following command to activate the module:

# sudo a2enmod rewrite

Step #1: Enable mod_rewrite

 

 

 

 

Now, a confirmation message will be displayed indicating success or that the module was already enabled.

Next, restart your Apache service with the following command to make the changes take effect:

# systemctl restart apache2

You have now successfully enabled the Apache 2 rewrite module.

Step #2: Configure .htaccess to Override Website Config

Next, you need to configure Apache to allow the use of .htaccess files, which contain the URL rewriting rules. The .htaccess file allows users to define the rewrite rules specific to a directory without accessing server configuration files.

We will now set up a .htaccess file for rewrite rule management. In most cases, the .htaccess file might already exist in your website’s document root directory (often /var/www/html).

If not, create one in the desired directory within your website’s structure with the following command that uses the touch command:

# sudo touch /var/www/html/.htaccess

By default, Apache does not allow the use of a .htaccess file. Therefore, you need to edit the configuration of each website’s virtual host file.

Next, open the default Apache configuration file (apache2.conf) in your preferred editor:

# sudo nano /etc/apache2/apache2.conf

Search for the following statements in this file:

<Directory /var/www/html>

Options Indexes FollowSymLinks MultiViews

AllowOverride None

Require all granted

</Directory>

Replace the AllowOverride None to All. The lines should read as follows:

<Directory /var/www/html>

Options Indexes FollowSymLinks MultiViews

AllowOverride All

Require all granted

</Directory>

Step #2: Configure .htaccess to Override Website Config

Once you have made the modifications, save the file and press Y to confirm the changes. Next, press CTRL + X to exit.

Next, restart Apache for the changes to take effect.

# sudo systemctl restart apache2

Now, the .htaccess file takes precedence over other configurations, enabling URL rewriting.

You have now successfully enabled the mod_rewrite in the Apache web server with an operational .htaccess file to govern your web application routing rules.

Step #3: mod_rewrite Directives

In the .htaccess file, URL rewriting actions are defined using various directives. Some of these directives include:

RewriteEngine Directive

The RewriteEngine is a component that activates or deactivates URL rewriting during runtime. Its syntax includes directives for rewriting URLs on an Apache server.

RewriteEngine On|Off

By default, the RewriteEngine is turned off. You can control its runtime processing by switching the directive on by editing the statement.

RewriteCond Directive

The RewriteCond directive sets the conditions for when rewrites occur. Its syntax is as follows:

RewriteCond TestString ConditionPattern [Flags]

Here,

RewriteCond is the keyword used to set a condition for a rewrite rule. You can have multiple condition directives before a single rule.

TestString includes plain text and can also have backreferences or server variables.

ConditionPattern is a Perl Compatible Regular Expression (PCRE) that applies to the TestString.

RewriteRule Directive

The RewriteRule directive defines the rules that the rewrite engine follows. Its syntax is as follows:

RewriteRule Pattern Substitution [Flags]

Here,

RewriteRule is the keyword used to define a single rule.

The pattern is a regex (Regular Expression) that matches a part of the requested URL.

Substitution is the actual URL to be directed by the Apache server.

[Flags] is an optional parameter that modifies how the expression behaves.

RewriteMap Directive

RewriteMap directive maps a key to a value for more complex rewriting tasks. Its syntax is as follows:

RewriteMap MapName MapType:MapSource [MapTypeOptions]

Here,

RewriteMap is the keyword used to define the mapping function.

MapName is the name of the function and the way to reference it to a RewriteRule.

MapType indicates the file type of MapSource. MapTypeOptions vary depending on MapType.

MapSource is the actual path to the file containing the mapping information.

Test mod_rewrite Functionality

To test whether mod_rewrite is working or not, fill the .htaccess file with some garbage text.

Save and then open some files from that folder in the browser.

You should get a 500 Internal Server Error and a .htaccess error in the Apache log file. This shows that mod_rewrite is enabled and operational.

Now, put the following rewrite rules in the .htaccess file

RewriteEngine on

RewriteRule ^foo/bar$ foo.php?id=bar [L]

In the .htaccess file, this configuration enables the rewrite engine and applies the rewrite rule, ensuring that any requests to /foo/bar are handled by foo.php?id=bar.

URL Rewrite Examples

Now that you know how to enable and configure mod_rewrite, let us see the module in action!

Example #1: Redirect From One Page to Another

Imagine you’ve updated a page’s content but want to keep the old URL for consistency. Here mod_rewrite can seamlessly redirect requests for the old page to the new one.

The .htaccess file looks like the following in this scenario:

RewriteEngine On

RewriteRule ^old.html$ new.html [NC]

Example #1: Redirect From One Page to Another

Here,

RewriteEngine On: Activates URL rewriting.

RewriteRule ^old.html$ new.html [NC]: Includes the RewriteRule directive to add the rewrite URLs logic on an Apache server.

^old.html$: Matches URLs starting with old.html and ending exactly there (no trailing characters).

new.html: The target URL to redirect users to.

[NC]: Makes the matching case-insensitive (e.g., Old.HTML also rewrites).

When someone tries to visit the old page, the server displays the content from the new.html page instead.

Example #2: Backreferencing RewriteRule Parameters

For a user accessing a URL in the following format:

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

The rewritten URL request has the following format:

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

Here, the mod_rewrite translates URLs into HTTP requests that the server can comprehend and handle. For this, add the following directives to the .htaccess file:

RewriteEngine On

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

Example #2: Backreferencing RewriteRule Parameters

Example #3: RewriteCondition Directive

The RewriteCond directive sets up a condition for RewriteRules. This condition determines when the RewriteRule should be applied.

For instance, if you migrate all web page extensions from HTML to PHP, the condition redirects requests ending in .html to .php.

Here’s what the .htaccess file may look like:

RewriteEngine On

RewriteCond %{HTTP_HOST} !php$

RewriteRule "^(.*).html$" "$1.php"

Example #3: RewriteCondition Directive

Here,

%{HTTP_HOST} represents the test string.

!php$ is the condition pattern, searching for all requests that don’t end with .php.

The RewriteRule only executes if the RewriteCondition is true. Here’s the rewrite:

“^(.*).html$” is the pattern match. It specifically looks for requests that start with any characters and end with .html.

“$1.php” is the substitution. The $1 backreferences the string before .html (captured by (.*)) and adds .php at the end.

The RewriteCond directive allows for page migration by enabling quick redirects from old pages or domains to new ones.

Example #4: RewriteEngine Directive

The RewriteEngine directive is the starting point for every .htaccess file. Turning the RewriteEngine on or off determines whether the rewrites occur. This feature is useful for debugging and testing.

Another use of the RewriteEngine is to comment sections in the .htaccess file. For example, consider the following set of statements:

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

Example #4: RewriteEngine Directive

 

When you turn off the RewriteEngine for rules and conditions, mod_rewrite does not execute the rewrite rules until the engine is on again.

Example #5: RewriteMap Directive

The RewriteMap directive improves rule substitution strings. For instance, consider the following URL structure:

http://example.com/product/database

The rewrite requirement is:

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

Instead of manually searching for the product ID, use RewriteMap and provide a file with key-value pairs containing the product names and IDs.

This example shows how to map from a file.txt containing key-value pairs:

database 272

server 273

cloud 274

Here’s what the rewrite set of statements looks like:

RewriteEngine On

RewriteMap prodID "txt:/path/to/file.txt"

RewriteRule "^product/(.*)" "products.php?id=${prodID:$1}"

Example #5: RewriteMap Directive

Here,

file.txt contains key-value pairs. RewriteMap uses this file as a reference.

prodID is the map name. It is used to reference the function in the rewrite rule substitution.

(.*) represents the string in the URL, such as the product name (database, server, cloud). The map function searches file.txt for the corresponding ID.

${prodID:$1} maps the product name to an ID and returns the ID from the file.

The RewriteMap directive supports different map types, which is essential for rewriting URLs with Apache mod_rewrite.

Conclusion

Configuring mod_rewrite allows you to create cleaner, more user-friendly URLs, improve SEO, and manage redirects efficiently.

By enabling the RewriteEngine, setting up .htaccess with appropriate RewriteCond and RewriteRule directives, and using RewriteMap for complex mappings, you can effectively control how your server processes and responds to URL requests. With these tools, you can ensure a smooth transition during migrations and maintain a secure, organized website structure.

FAQs

Q. What is mod_rewrite?

mod_rewrite is an Apache module that rewrites URLs to make them more user-friendly or to redirect them.

Q. How do I enable mod_rewrite?

Enable mod_rewrite with $ sudo a2enmod rewrite. Then, restart Apache by executing $ sudo systemctl restart apache2.

Q. Where do I put mod_rewrite rules?

Put mod_rewrite rules in the .htaccess file or in the Apache configuration files like httpd.conf or within your site’s <VirtualHost> block.

Q. How do I use mod_rewrite with virtual hosts?

Add rewrite rules in the <VirtualHost> section of your site’s config file and restart Apache.

Q. What does RewriteEngine On do?

RewriteEngine On activates the rewrite engine to execute the rules.

Q. How do I create a basic rewrite rule?

Use RewriteRule to define a rewrite. For example, redirect /old to /new:

RewriteEngine On

RewriteRule ^old$ /new [R=301,L]

Q. What does [R=301,L] mean?

[R=301,L] means a permanent redirect and stop processing more rules.

Q. How do I map a URL to a different filesystem path?

Rewrite a URL to a filesystem path like the following:

RewriteEngine On

RewriteRule ^old/(.*)$ /new/$1 [L]

Q. How do I apply rules to a specific directory?

Put your .htaccess in that directory or use a <Directory> block in the config file.

Q. Why isn’t mod_rewrite working?

Ensure mod_rewrite is enabled, RewriteEngine On is set, and the syntax is correct. Also, check Apache’s error log and restart Apache after changes

Try this guide with our instant dedicated server for as low as 40 Euros