Apache mod_rewrite module: A Developer’s Guide

Updated: January 20, 2024 By: Guest Contributor Post a comment

Introduction

The Apache mod_rewrite module is a powerful and sophisticated tool for URL manipulation and a staple for web developers. Often employed for SEO-friendly URLs, its use cases range from simple redirection to complex rewriting rules that elevate the flexibility and security of websites. In this guide, we’ll explore the intricate world of mod_rewrite from basic examples to advanced tricks.

Prerequisites

  • Apache HTTP Server
  • Basic knowledge of regular expressions
  • .htaccess file access or Apache server config file access

Enabling mod_rewrite

To work with mod_rewrite, it is crucial to ensure that it’s enabled. Here’s how you can check and enable mod_rewrite in Apache:

# Check if mod_rewrite is enabled
a2enmod rewrite

# Restart Apache to take effect
systemctl restart apache2

Basic Redirection

Starting with a straightforward redirect, we’ll write a rule that directs users from an old page to a new one.

RewriteEngine On
RewriteRule ^oldpage.html$ newpage.html [R=301,L]

The R=301 flag is for search engine-friendly permanent redirections, and L indicates that this rule should be the last one processed if matched.

Restructuring URLs for Readability

One of the most common uses of mod_rewrite is to make dynamic URLs user-friendly. Look at this example converting a dynamic URL into a static-looking one:

RewriteEngine On
RewriteRule ^user/([0-9]+)/?$ profile.php?id=$1 [NC,L]

Here, NC makes the rule case-insensitive, ensuring that the URL /User/123 will work just as /user/123.

Securing Directories

Mod_rewrite can also be used to enhance security by blocking access to specific files or directories. Below we secure a directory by restricting direct access to files with certain extensions.

RewriteEngine On
RewriteRule ^private-files/.*\.(txt|md)$ - [F]

The F flag returns a 403 Forbidden response, protecting your sensitive files.

Domains and subdomains

Managing domains and subdomains effectively is essential, and mod_rewrite allows complex rules like redirecting from www to non-www:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

This snippet detects if a URL starts with www and removes it, all while preserving the rest of the URL.

Complex Rewrite Conditions

Let’s ramp up the complexity now by combining conditions to create a more intricate rule:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?page=$1 [QSA,L]

This attempts to rewrite only if the requested filename is neither a directory nor an existing file, appending the query to index.php. The QSA flag ensures that existing query strings are preserved.

Handling SSL and Canonical Hostnames

An advanced scenario for mod_rewrite is forcing SSL encryption. Below is an example that redirects all non-SSL traffic to HTTPS and ensures the canonical domain is used.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTP_HOST} !^mydomain.com$ [NC]
RewriteRule (.*) https://mydomain.com/$1 [R=301,L]

Separate rules handle the SSL and canonical domain redirections, both employing the R=301 rule.

Conclusion

Apache’s mod_rewrite module offers web developers tremendous power and flexibility for URL manipulation. Whether for aesthetic, practical, or security reasons, learning to wield these tools effectively can lead to enhanced website performance and user experience. With practice, the possibilities offered by mod_rewrite become nearly limitless.