DNS Lookup, Reverse DNS Lookup, Domain Configuration Check and IP Address Calculators

Using Mod_Rewrite

This isn't an extensive tutorial on using mod_rewrite. I'm just documenting some experiences I've had using rewrite rules. For more information on mod_rewrite see the Apache mod_rewrite documentation http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html or http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html.

Rewrite rules can be added to a .htaccess file in the local folder, or they can be added to the Apache httpd.conf file.

Apache reads the httpd.conf file when it starts up. So after making changes to the httpd.conf file you need to restart Apache for the changes to take effect. The .htaccess file is read with each HTTP request. So changes made to the .htaccess file take effect immediately. This also means that rewrite rules specified in the .htaccess file cause extra overhead as they are loaded with each request.

The examples I've shown here work in a .htaccess file (with the exception of the rewrite log example). You may need to modify the rules slightly to make them work in the httpd.conf file (like adding a leading / to the beginning of the path to match).

Note that rewrite rules that apply a match to a scriptalias folder (eg. /cgi-bin/) will not work in a .htaccess file.

Redirect Homepage

These rules allow you to redirect users to a homepage or script. The following pages requests will get redirected to www.example.com/homepage.

Options +FollowSymlinks
rewriteEngine on
RewriteRule ^default\.html$ http://www.example.com/homepage [R]
RewriteRule ^index\.html$ http://www.example.com/homepage [R]
RewriteRule ^$ http://www.example.com/homepage [R]

The [R] at the end of the rewrite rule returns a redirect to the browser. This makes the browser update the URL that it shows on the screen. Using [R] will return a 302 (temporarily moved) HTTP response code to the browser. If you want to return a 301 (permanently moved) HTTP response code use [R=301].

Note that the dot in the match expression needs to be escaped with a backslash (\). This is because a dot has a special meaning in regular expressions.

Force Requests to Begin With www

This rule detects requests that begin with example.com and rewrites them to www.example.com.

Options +FollowSymlinks
rewriteEngine on
rewriteCond %{HTTP_HOST} ^example\.com [NC]
rewriteRule ^(.*)$ http://www.example.com/$1 [R=301]

One or more rewrite conditions can precede a rewrite rule. The rewrite rule will only get executed if the rewrite condition is true. The rewrite condition in the example above means that the rewrite rule will only get executed if the HTTP request begins with example.com.

On the next page we'll use rewrite rules to hide file extensions and convert pages to URL parameters...