Getting Started: Apache mod_rewrite Methods

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} ^(.*)$
RewriteCond %{HTTP_HOST} !^$
RewriteRule (.*)$1 [P]

Or if you want to force — even if visitors use to get to your site:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^$ [NC]
RewriteRule ^(.*)$$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} ^$
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} ^$
RewriteRule ^(.*)$$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^$
RewriteRule ^(.*)$$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.

Allows to rewrite to

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


Category: open source Time: 2004-11-05 Views: 2

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C), All Rights Reserved.

processed in 0.203 (s). 12 q(s)