Using .htaccess to redirect a folder and all of its contents
I'm currently doing some Autumn cleanup here on Ghacks. One of the things that I have sworn myself to tackle in this period is to fix all the not found 404 errors that Google Webmaster Tools is reporting. I started with an analysis of the error urls to find out if there are patterns that I can address elegantly with some redirection magic.
Turns out that the majority of errors come from the former forum which is no longer available. The idea was then formed to redirect the forum and all of its files and subfolders to the root of the website to resolve all errors at once.
My preferred way of doing that is using .htaccess. While not everyone may have access to it, it is preferable over many comparable solutions such as meta tag refreshes or using plugins.
You find the .htaccess file in the root of your public HTML folder normally. You can edit it like a normal text document. I'd recommend you create a backup of the file first before you add or remove any contents.
You only need one line of code to redirect a web folder, all of its files, subfolders and the files they contain.
RedirectMatch 301 ^/forum/.*$ https://www.ghacks.net/
This tells the web server to redirect all requests pointing to https://www.ghacks.net/forum/ urls to the main domain instead. You can alternatively use a different domain or even a page by simply editing the http:// address.Â One option here would be to create a page that provides users who request forum pages with information why they are being redirected.
Save the directive afterwards and try to load some of the urls that you have redirected. If you do not have any at hand, just make them up as they should all be redirected to the root domain or the address you have specified.
You can add additional folders by copying the line and editing the folder information in each of the new directives. It may take weeks before the changes are reflected by Google's Webmaster Tools.Advertisement
RedirectMatchisn’t necessary. It’s better to use
Redirectwhich is both simpler and faster.
For example, your code above would become:
Redirect 301 /forum/https://www.ghacks.net
Redirect 301 /dir https://www.ghacks.net
Redirect 301 /search https://www.ghacks.net
But that does not redirect everything, e.g. a file in a subdirectory to the root directory?
Sorry, I misinterprated, You are right; it would redirect requests to
https://www.ghacks.net/somepage. My bad :(
BTW, the first line of the code in my first comment is incorrect. It should read:
Redirect 301 /forum https://www.ghacks.net