Rewriting URLs with mod_rewrite Apache

User avatar
Site Admin
Posts: 35
Joined: Sun Jul 03, 2016 2:17 pm
Location: India

Rewriting URLs with mod_rewrite Apache

Postby admin » Sun Jul 03, 2016 5:07 pm

Firstly, you'll need to put the following code in a file named .htaccess, in whichever directory you are dealing with:

Code: Select all

RewriteEngine on

Now the mod_rewrite module has been turned on, and is ready to accept further instructions. The RewriteRule command is the root of the module, which tells mod_rewrite what to do. Here is its syntax:

RewriteRule Pattern Substitute (Optional Flags)

Here's an example:

Code: Select all

RewriteRule /articles/([0-9]+) /articles.php?id=$1

This will replace with

You don't have to limit yourself to numbers either, you can use [a-z] or [A-Z] too!

Here are some flags you can use:

* f: send a 403 forbidden error to the browser
* NC: make the rule case-insensitive
* g: send a 410 gone error to the browser

Not only can you rewrite URLs using rules, but you can also add conditions to these rules, so they won't be executed in every case:

RewriteCond Test Condition

Here's an example of what you can do with conditions:

Code: Select all

RewriteCond %{HTTP_USER_AGENT} ^Opera.*
RewriteRule ^/$ /index_opera.php [L]

RewriteCond %{HTTP_USER_AGENT} ^Netscape.*
RewriteRule ^/$ /index_netscape.php [L]

RewriteRule ^/$ /index.php [L]

This will load a special page for Opera and Netscape, and load a default page for people not using Netscape. Here are some variables you can use in your conditions:

* HTTP_USER_AGENT (browser)
* HTTP_REFERER (referring page)
* HTTP_HOST (domain name -
Finest web hosting solution at the most affordable rates
Cheap Website Hosting
cheap VPS hosting india

Return to “Scripts / Code Snippets”

Who is online

Users browsing this forum: No registered users and 0 guests