mod_rewrite and basic examples

ModRewrite is a powerful feature of the Apache web server. It provides an easy way to modify/manipulate URLs. As complicated as it sounds a regular webmaster can benefit from this feature in many way. I will list here the ones I consider most useful for the regular webmaster.

Some Examples :

I) Rewriting event.php?id=210 to event-210.html

It is a simple redirection in which .php extension is hidden from the browser’s address bar and dynamic url (containing “?” character) is converted into a static URL.

RewriteEngine on
RewriteRule ^event-([0-9]+)\.html$ event.php?id=$1

II) Rewriting event.php?id=12 to event/sportsday/10.html

SEO expert always suggest to display the main keyword in the URL. In the following URL rewriting technique you can display the name of the product in URL.

RewriteEngine on
RewriteRule ^event/([a-zA-Z0-9_-]+)/([0-9]+)\.html$ event.php?id=$2

III) Redirecting non www URL to www URL

If you type in browser it will be redirected to If you want to do same with your website then put the following code to .htaccess file.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^themoderneducation\.com$
RewriteRule (.*)$1 [R=301,L]

IV) Create easy to remember URLs or also known as COOL URIs,

other call them Search Engine Friendly URLs. For example you have some complicated site driven by some server-side scripting language: PHP, Perl, etc. In general its URLs will look like

It is not easy to remember such URL.

Using ModRewrite you can make the URL look like:

Here is the code:

RewriteEngine On
RewriteRule ^([a-z]*)/([a-z]*)/([1-9]+)(-[1-9]+)? $$2&a=$3&page=$4&lang=$1 [L]


V) Rewriting to

Have you checked you type in browser you can see my profile over there. If you want to do the same kind of redirection i.e to then you can add the following code to the .htaccess file.

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ user.php?username=$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ user.php?username=$1

VI) Redirecting the domain to a new subfolder of inside public_html.

Suppose the you’ve redeveloped your site and all the new development reside inside the “new” folder of inside root folder.Then the new development of the website can be accessed like “”. Now moving these files to the root folder can be a hectic process so you can create the following code inside the .htaccess file and place it under the root folder of the website. In result, point out to the files inside “new” folder.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^themoderneducation\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.themoderneducation\.com$
RewriteCond %{REQUEST_URI} !^/new/
RewriteRule (.*) /new/$1

The official ModRewrite documentation can be found at:


Written by 

2x Salesforce MVP | Platform Champion | 18x Salesforce Certified | MuleSoft Certified | 8x Trailhead Ranger | TechForce Services | Sydney | Australia

Leave a Reply

Your email address will not be published. Required fields are marked *