Rewrite Rules: Practical Examples
Apache Rewrite Rules can be used to transform a pretty ugly looking URL into a beautiful, SEO-friendly and meaningful URL. I would like to list a couple of real-world examples below to explain how Rewrite Rules can be set up and how they work. Rewrite Rules use Regular Expressions, so this article is closely related to my Regular Expressions article.
Introduction
The Rewrite Rules can be added either to your httpd.conf file of your Apache installation or to a .htaccess file. Either way, before these rules can be used, it is good practice to check if mod_rewrite is available and then switch on the rewrite engine, like:
<IfModule mod_rewrite.c>
RewriteEngine On
[Your Rewrite Rules Here]
</IfModule>
“domain.com/new/” to “index.php?page=new”
RewriteRule ^([A-Za-z0-9-]+)/?$ index.php?page=$1
Explanation
- ^: pattern should match from the beginning of the string
- (: start of subpattern
- [A-Za-z0-9-]: class of characters
- +: one or more times
- ): end of subpattern
- /: foward slash…
- ?: can occur zero or once
- $: end of string
“domain.com/contact.html” to “index.php?page=contact”
RewriteRule ^(.*).html$ index.php?page=$1 [QSA]
Explanation
- ^: pattern should match from the beginning of the string
- (: start of subpattern
- .: one or more of…
- *: …any character
- ): end of subpattern
- .html: followed by “.html”
- $: end of string
The subpattern “(.*)” will then be passed on to index.php as $1 parameter. [QSA] (Query String Append) means that additional parameters in the querystring will be passed on as well, e.g.
domain.com/contact.html?param1=done
will be rewritten to
domain.com/index.php?page=contact¶m1=done
Resources
- Apache Module mod_rewrite
- Apache Rewrite Cheatsheet
- URL Rewriting
- mod_rewrite Cheat Sheet
- URL Rewriting for Beginners
- Stupid htaccess Tricks – redirects