Welcome to web 2.0 Blog

The Last news of the web Development from the world master's

10+ Mod_Rewrite Rules You Should Know

Posted by web2.0 Design resourse Friday, August 28, 2009

Mod_rewrite is an Apache-based rewrite engine for dynamically rewriting URLs. It’s built into Apache servers natively, though not enabled by default.
It’s capable of functions beyond simple rewrites, though, some of which are included below.

Turn Mod_Rewrite On

Mod_rewrite is used through your .htaccess file. Place the following code at the beginning of your .htaccess file to turn mod_rewrite on:

RewriteEngine on
(Don’t forget that .htaccess commands are case-sensitive.) This code needs to be entered at the beginning of any .htaccess file using mod_rewrite.

The Basic Mod_Rewrite Layout

The basic format for a mod_rewrite command is:

RewriteRule Pattern Substitution [Flag(s)]

URLs are Always Relative

The URL you redirect to is always relative to the directory in which your .htaccess file is placed. So if it’s in the root directory, URLs are all in relation to the root directory; if it’s in a sudirectory, URLs are in relation to that particular subdirectory.
A Basic Redirect

If you just want to create a simple 301 redirect from one URL to another, then use the following code:

RewriteRule ^fileone.html$ filetwo.html

This is a very basic rule that means any requests for fileone.html will be sent to filetwo.html.

Require no “www”

This bit of code will make it so visitors to your site don’t need to type in the “www” bit of your website address.

RewriteCond %{HTTP_HOST} !^domain\.com$ [NC] 

RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]  

Block a Specific IP Address

If you want to block someone coming from a specific IP address from accessing your website, you can use the following code:

RewriteCond %{REMOTE_ADDR} ^(A\.B\.C\.D)$  

RewriteRule ^/* http://www.domain.com/sorry.html [L] 

Replace the A\.B\.C\.D with the IP address you want to block (don’t forget to leave the “\” before each dot, which escapes the character).


Post a Comment


free counters