How Does Mod_Rewrite Work For Pretty Links?

Published August 27, 2024

Problem: Creating Pretty URLs with Mod_Rewrite

Mod_rewrite is an Apache module that allows URL rewriting. This is useful for creating readable URLs that improve user experience and search engine optimization. However, using mod_rewrite can be difficult. It requires knowledge of regular expressions and server setup.

Mod_Rewrite Functionality

Rewrite Rules Basics

Rewrite rules are the main part of mod_rewrite's functionality. They let you change URLs before the web server processes them. This is useful for creating user-friendly URLs, redirecting old pages to new ones, or handling complex routing logic.

The basic syntax of a rewrite rule is:

RewriteRule Pattern Substitution [Flags]
  • Pattern: A regular expression that matches the incoming URL
  • Substitution: The new URL or file path to use
  • Flags: Optional parameters that change the rule's behavior

Here are some examples of rewrite rules:

  1. Add .php to all requests:

    RewriteRule ^(.*)$ $1.php
  2. Redirect all traffic to HTTPS:

    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  3. Create a simple pretty URL:

    RewriteRule ^product/([0-9]+)$ product.php?id=$1

Tip: Test Your Rewrite Rules

Use the [R] flag temporarily to see the rewritten URL in your browser's address bar. This helps you debug your rules without affecting the actual page content.

Regular Expressions in Mod_Rewrite

Regular expressions (regex) are important in mod_rewrite. They help you create flexible patterns that match various URL structures. With regex, you can capture parts of the URL and use them in the rewritten version.

Some common regex patterns used in mod_rewrite:

  • ^: Matches the start of the string
  • $: Matches the end of the string
  • (.*): Captures any character (except newline) zero or more times
  • ([0-9]+): Captures one or more digits

Capturing and replacing URL patterns is a useful feature. For example:

RewriteRule ^article/([0-9]+)/([a-z-]+)$ article.php?id=$1&title=$2

This rule would change a URL like /article/123/my-article-title into article.php?id=123&title=my-article-title.

To learn more about regular expressions, these resources are helpful:

  1. Regular-Expressions.info: A guide to regex
  2. RegexOne: An interactive tutorial for learning regex
  3. RegExr: An online tool for testing regex patterns