Here’s my second tutorial about .htaccess, the first one was about making your own custom 404-error page. This one is about redirecting with .htaccess. In this tutorial I’ll explain the benefits of using .htaccess to redirect, instead of PHP or Javascript and I’ll show some examples about how to use .htaccess redirects.
Why?
There are a couple of reasons for using .htaccess redirects instead of PHP or even Javascript. First of all, it’s very simple. There is no need to edit any files, you just need to change the .htaccess file. Imagine you need to redirect a whole directory of your site, with hundreds of pages. If you would use Javascript, you had to change every file, or at least use some search and replace commands to get the javascript on every page. With .htaccess you can easily redirect a whole directory.
It’s easy, but it’s also better for SEO to use .htaccess redirects. You can specify the type of your redirect, either temporarily (302) or permanent (301). You can’t do that with Javascript.
So now you know why you should use .htaccess redirects, now let’s take a look to how you use it.
How?
If you haven’t made a .htaccess file yet, make one. See the previous tutorial for details.
This is the basic syntax of a .htaccess redirect:
Redirect /olddirectory http://www.newdomain.com/newdirectory
But if you want to redirect that directory permanent, don’t forget to add 301 or permanent:
Redirect 301 /olddirectory http://www.newdomain.com/newdirectory
Redirect permanent /olddirectory http://www.newdomain.com/newdirectory
Redirecting a whole site
You can use this code to redirect a whole site to a new domain:
Redirect 301 / http://www.newdomain.com/
RedirectMatch
You can use redirectmatch for some more complicated redirects. Let’s take a look at the previous example, where I used Redirect 301 to move a whole site. I you would go to http://www.olddomain.com/contact you would be redirect to http://www.newdomain.com/. So it doesn’t matter what you incoming page is, you would always be redirected to the homepage of the new domain. If you don’t want that to happen then you can use Redirectmatch to redirect your whole site. This code will redirect a visitor (or search engine) to the same file at the new domain:
RedirectMatch 301 ^(.*)$ http://www.newdomain.com/
Did this tutorial helped you? Please leave a comment and tell how this tutorial helped you.


1
Thanks it helped a lot redirecting some folders in my website!
2
You’re welcome! Thanks for commenting