Apache URL Rewriting

Apache mod_rewrite is a functional, flexible module to rewrite URL's on the fly. You can use it to create fancy, SEO friendly URL's, create redirect pages and prevent hotlinking. Understanding of regular expressions is recommended as mod_rewrite makes use of them.

To use mod_rewrite the module has to be loaded. Open /etc/httpd/conf/httpd.conf find and uncomment by removing the # in the line:

#LoadModule  rewrite_module  modules/mod_rewrite.so

After uncommenting (or adding) this line restart Apache:

/etc/init.d/httpd restart

The next steps you might either write in the server config (/etc/httpd/conf/httpd.conf) or by using .htaccess files. In my example I will use a .htaccess file.

Create a new file named .htaccess in the root directory of your webserver and add the these lines:

Options +FollowSymLinks
RewriteEngine On

This lines will enable mod_rewrite

A simple rewrite rule to make a permanent rewrite of example.htm or example.html to index.html could be:

RewriteRule ^example\.(htm|html)$ index.html [R=301,L]

Explaination: Rewrite every url beginning (^) with example and ending ($) with htm OR (|) html permanent (R=301) to index.html. If you want to redirect every url ending with example.htm the line would be

RewriteRule example\.htm$ index.html [R=301,L]

To redirect every url containing example.htm to index.html:

RewriteRule example\.htm index.html [R=301,L]

or redirect every url starting with example.html to index.html

RewriteRule ^example\.(htm|html)$ index.html [R=301,L]

Please login first before adding a comment.


You are here: Home Howtos and FAQs Apache Apache URL Rewriting