One of the common and popular way to redirect your visitors is to use an .htaccess redirect. Before a page is served to the browser the server checks first for an .htaccess file and the visitors will be redirected to the new page.301 redirect is the most efficient method for webpage redirection.Also this method is a Search Engine Friendly method for web page redirection.
Read:How to specify your own ErrorDocuments using .htaccess file?
Let us see how do we set different types of redirection by using .htaccess file.
The following is the generic syntax to do the redirection.
Redirect /dir1/file1.html http://abcd.com/dir2/newfile.html
1. Redirect the site from without www to with www
This is used to redirect all users who access the site without the www. prefix.For example if you want to redirect all requests which are pointing to http://abcd.com/ to http://www.abcd.com.
Add the following line to the .htaccess file
1 2 3 4 5 | # mod_rewrite in use Options +FollowSymlinks RewriteEngine On RewriteCond %{http_host} ^abcd.com [NC] RewriteRule ^(.*)$ http://www.abcd.com/$1 [R=301,L] |
2. Redirect the site from with www to without www
This is used to redirect all users to access the site with the www. prefix.
This is another common requirement.For example if you want to redirect all requests which are pointing to http://www.abcd.com/ to http://abcd.com. This can be easily achieved by adding a few lines of code into the .htaccess file.Even You can make your webserver so that if someone requests http://www.abcd.com/, it does a 301 (permanent) redirect to http://abcd.com/
Add the following line to the .htaccess file
1 2 3 | RewriteEngine On RewriteCond %{HTTP_HOST} !^www.abcd.com$ [NC] RewriteRule ^(.*)$ http://abcd.com/$1 [L,R=301] |
3. Redirect index.html to a specific sub-folder
You can redirect your default index file to a different directory or file.
Add the following line to the .htaccess file
1 2 3 | # Redirect index.html to a newdirectory subfolder Redirect /index.html http://globinch.com/newdirectory/ |
4. Redirect the entire site to a different URL
Add the following line to the .htaccess file
1 2 3 | # Redirect your entire website to any other domain Redirect 301 / http://globinch.com/ |
5. DirectoryIndex to redirect to specific index page:
1 2 | # Specify Specific Index Page DirectoryIndex index.html |
6. Redirect to secure version of your domain
This allows the users to redirect to secure site (https://)
Add the following line to the .htaccess file
1 2 3 | RewriteEngine On RewriteCond %{SERVER_PORT} 80 RewriteRule ^(.*)$ https://www.abcd.com/$1 [R,L] |
Related articles
- 7 steps to Speed up website loading – Website Optimization Tips -Part 1
- Speed up website -Compress CSS/JavaScript using GZIP/DEFLATE compression – Optimization Tips -Part 2
- Check website/ web page for css/script Gzip/ Deflate compression – Optimization Tips -Part 3
Before you go, subscribe to get latest technology articles right in your mailbox!.