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:
-
Add .php to all requests:
RewriteRule ^(.*)$ $1.php
-
Redirect all traffic to HTTPS:
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
-
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:
- Regular-Expressions.info: A guide to regex
- RegexOne: An interactive tutorial for learning regex
- RegExr: An online tool for testing regex patterns
Implementing Pretty Links with Mod_Rewrite
Common Rewrite Rule Patterns
Mod_rewrite offers patterns to create pretty links. Here are some common patterns:
-
Rule for appending file extensions:
RewriteRule ^([^.]+)$ $1.php [L]
This rule adds a .php extension to URLs without one. For example,
/about
becomes/about.php
. -
Rule for routing all requests through a single file:
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
This pattern sends all requests to
index.php
, passing the original URL as a parameter. It's useful for front-controller patterns in frameworks. -
Use cases for different rule patterns:
-
SEO-friendly product pages:
RewriteRule ^product/([0-9]+)/([a-zA-Z0-9-]+)$ product.php?id=$1&name=$2 [L]
This changes
/product/123/blue-shirt
toproduct.php?id=123&name=blue-shirt
. -
Blog post URLs:
RewriteRule ^blog/([0-9]{4})/([0-9]{2})/([a-zA-Z0-9-]+)$ blog.php?year=$1&month=$2&title=$3 [L]
This transforms
/blog/2023/05/summer-trends
toblog.php?year=2023&month=05&title=summer-trends
.
Example: Category-based URL Rewrite
RewriteRule ^category/([a-zA-Z0-9-]+)$ category.php?name=$1 [L]
This rule transforms URLs like /category/electronics
to category.php?name=electronics
, allowing for clean, category-based URLs.
Configuring Mod_Rewrite
Mod_rewrite configuration depends on your server setup and needs.
- Where to place rewrite rules:
-
Server configuration file (e.g.,
httpd.conf
):- Applies to the entire server
- Requires server restart to apply changes
- Example:
<VirtualHost *:80> ServerName example.com DocumentRoot /var/www/html RewriteEngine On RewriteRule ^about$ about.php [L] </VirtualHost>
-
.htaccess
file:- Applies to specific directories
- Changes take effect immediately
- Example content of
.htaccess
:RewriteEngine On RewriteRule ^products/([0-9]+)$ product.php?id=$1 [L]
- Enabling mod_rewrite in Apache:
To use mod_rewrite, make sure it's enabled in your Apache configuration:
- Open your Apache configuration file (often
httpd.conf
orapache2.conf
) - Find or add this line:
LoadModule rewrite_module modules/mod_rewrite.so
- Restart Apache to apply changes
Test your rewrite rules to avoid unexpected behavior on your website.
Tip: Use RewriteLog for Debugging
Enable RewriteLog to troubleshoot your rewrite rules:
- Add these lines to your Apache configuration:
RewriteLog "/path/to/rewrite.log" RewriteLogLevel 3
- Restart Apache and check the log file for detailed information about how your rewrite rules are processed.