Redirect Sub-domain Folder to Sub-domain URL – For Beginners
If you’ve ever run into the need or desire to run a website using a sub-domain, this post may help you. I got stuck with this particular issue and even though it was such a simple fix, it eluded me for quite some time!
As a quick refresher for those new to domains and web development, creating a sub-domain usually results in the creation of a directory inside the public_html folder of the root domain. For example, let’s say you’re running a WordPress blog on the domain example.com and now you want to create a forum for online discussions at the domain, forums.example.com.
After creating the sub-domain, you have forums.example.com, but you also have example.com/forums. It’s in this location that you would install your script’s files and directories. In most cases, this doesn’t matter much since you’ll only be using the sub-domain for marketing and linking purposes anyway.
The problem with the aforementioned configuration is that search engines will see duplicate content because they will think that forums.example.com and example.com/forums are two different websites. It also presents an un-attractive experience for your users. What we want to do is automatically redirect users to the correct URL.
The Solution
You will need to be familiar with working with .htaccess files. All you need to do is copy and paste the following code into the .htaccess file that resides in your root domain’s directory. In this case, you would place it in the root folder for example.com:
RewriteEngine On
RedirectMatch 301 ^/forums/(.*)$ http://forums.example.com/$1
This quick rule tells the browser to redirect any requests for example.com/forums to forums.example.com. The best part is that it will retain full URL structure. Don’t forget to change ‘forums’ and the domain to match your own variables.
My Two Cents
No matter how big or small your website is, you should always be returning valid URLs wherever possible. It just helps to keep the internet clean and functional. How often have you visited a website looking for something that is no longer there and with no help for how to find it again? Or how about when you load a site and all you get are redirect and/or server errors?
It’s not a fun experience and now you won’t have to worry about your visitors having any issues with your sub-domains!