Redirect all subdomains to www

If you ever need to redirect all your subdomains to a main subdomain like www, here is a method for you to easily accomplish that. I kept these notes from when I wanted to implement it for my own site: www.gidforums.com.

One day recently, Google started referring readers to a variety of subdomains for gidforums.com. I saw hits to mail.gidforums.com, pop.gidforums.com and of course, also to the naked domain itself: gidforums.com, and sometimes, even the IP address [69.30.244.38] too.

Because www.gidforums.com is served by an Apache web server, all I had to do was edit the virtual host configuration for the gidforums.com domain. Also, because the rewrite module was already enabled for the domain and site, I used that too. I just added the following lines to the (virtual host) configuration file for the gidforums.com domain and restarted the web server.

Read the official Apache Rewrite Module documentation here.

...
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule (.*) https://www.gidforums.com$1 [R=301,L]
...

Line no. 2 just checks the HOST string of every request to the virtual host and finds any that do not start with the string www.. If there is a match, the server will enforce the rewrite rule on line no. 3 and return a 301 Moved Permanently code and status message, together with the new location (URL), to the user’s browser.

Of course, in my virtual host configuration for gidforums.com, the line to enable the rewrite module for the domain was already there, but if you have not used the rewrite module or not already enabled it for your domain, your solution will probably look like this instead:

...
    RewriteEngine on
    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule (.*) http://www.example.com$1 [R=301,L]
...

Like I said, don’t forget to restart the web server after saving your changes!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>