Apache’s mod_rewrite module appears to be the one area of Apache administration that generates the most questions. I seem to be a perpetual beginner when it comes to url rewriting, and I continue to dream up impossible wishes on a regular basis.

I also bother my own peers for their best rewrite hacks to build up my arsenal. However, having seen numerous queries on this powerful module, I thought sharing some of my own favorite (and basic) rewriting usage would contribute to those seeking answers.

In addition, I am sure we have some hidden rewriting ninjas hanging around the SitePoint community that will add in some missing magic we all could leverage.

As a final aside – my knowledge of rewriting has come almost exclusively from reading and re-reading (and re-reading!) the Apache HTTP docs and some serious Googling on the topic over the years. Regular expressions can be both your friend and your enemy! ;>)

These are generally added into either your httpd.conf file or into an .htaccess file. For some excellent advice on htaccess if you are using that route – see this.

Re-directing a sub-domain to a domain:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*).mydomain.com$
RewriteCond %{HTTP_HOST} !^www.mydomain.com$
RewriteRule (.*) http://mydomain.com/%1$1 [P]

Or if you want to force www.mydomain.com — even if visitors use mydomain.com to get to your site:

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

Perhaps you have a directory you need to point visitors toward within the DocumentRoot that contains your entry pages (like a beta test site):

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www.betadomain.com$
RewriteCond %{REQUEST_URI} !^/beta/
RewriteRule ^(.*)$ /beta/$1

Re-directing users (and search engines) permanently to a new domain from an old domain during a migration (and letting them get to the page they wanted instead of just the new site’s root index page).

RewriteEngine on
RewriteCond %{HTTP_HOST} ^olddomain.com$
RewriteRule ^(.*)$ http://newdomain.com$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www.olddomain.com$
RewriteRule ^(.*)$ http://newdomain.com$1 [R=301,L]

And finally — I see many questions about search engine friendly url’s and dynamic pages. I have used this simple rewrite I learned from a friend – however – this is where some contribution would be great as I see these questions over and over in the forums. By all means add your best rewrite methods for working with dynamic pages. I do not use this last tactic too often and it is quite rudimentary.

Allow www.domain.com/news5.php to rewrite to www.domain.com/news.php?id=5

RewriteEngine on
RewriteBase /articles
RewriteRule ^news([^\.]+)\.php$ news.php?id=$1