Redirect URL with htaccess

January 18, 2010 by: Akhthar Parvez

If you want to redirect a page/directory to another page/directory, it’s plain simple. Just add the following line into your .htaccess file.

Redirect 301 /oldpage.html /new_directory/

Above rule will redirect all requests to the file /oldpage.html to the directory /new_directory/. Redirect number 301 means it was moved permanently. See all numbers below:

300 multiple choices (e.g. offer different languages)
301 moved permanently
302 found (originally temporary redirect, but now commonly used to specify redirection for unspecified reason)
303 see other (e.g. for results of cgi-scripts)
307 temporary redirect

**********************************************************************

If you want to redirect the pages on a website to another, you should use RewriteRule instead of Redirect. The syntax is given below:

Option 1 (this will redirect only the old domain to new domain:
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?newdomain\.com
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]

Option 2 (this will redirect all domains except the new domain to new domain):
Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.newdomain\.com
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]

If you want to redirect all requests without www to with www, use the following code.

Options +FollowSymLinks
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} ^sysadminguide\.com$ [NC]
RewriteRule ^(.*)$ http://www.sysadminguide.com/$1 [R=301,L]

Above rules would redirect the requests for sysadminguide.com to www.sysadminguide.com.

Similarly, you can redirect all the pages in a sub-drectory to the document root itself as below:

RewriteCond %{HTTP_HOST} ^sysadminguide\.com$ [NC]
RewriteRule ^topics/(.*)$ /$1

RewriteRule is a powerful tool to redirect website URLs and pages alike with the use of Regular expressions. To learn more about Apache rewrite module (mod_rewrite), goto the following link:

http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html

Leave a Reply

You must be logged in to post a comment.