Apache: redirect to subdomain via .htaccess

Redirecting to subdomains is pretty easy with apache using <VirtualHost> directives.
Problem is that such directives cannot be set in .htaccess file (only in .httpd.conf or equiv.) so we must find a workaround when server config files are not accessible (as with shared hosting…).

The solution is to use mod_rewrite possibilities, provided your host activated .htaccess & mod_rewrite in apache…

In my case, I simply want to redirect all queries without ‘www’ subdomain to ‘www’ subdomain.
Here is my .htaccess content:

RewriteEngine On
RewriteBase /
RewriteCond %{SERVER_NAME} ^mydomain.com$ [NC]
RewriteRule ^(.*)$ http://www.%{SERVER_NAME}/$1 [L,R=301]

Line by line, we did this:

  • first we activate url-rewriting engine (“RewriteEngine On”)
  • we say that our rule apply to entire folder content, starting at top (folder where .htaccess is located) folder
  • here is the core of our operation: we test the value of {SERVER_NAME} variable which contains queried hostname.
    • we ensure queried hostname is our domain name without any subdomain prefix (using special characters ^ and $ around our domain name)
    • we append [NC] to tell rewrite engine to perform a case insensitive check on queried domain name
  • finally we write our rule, just below RewriteCond so that it will apply to all urls matching our condition.
    basically we simply redirect all queries to our hostname after having prefixed it with our ‘www’ subdomain.
    at the end of the line, [L,R=301] stands for:

    • L = Last = we tell apache to stop rewrite process here and not look more after that point
    • R=301 means our redirect will return ‘code 301’ which will tell browser and search-robots that the change of address is permanent (ie. next time they will directly query the url we’re redirecting to)

I hope it helped!


Post a Comment

Your email is never published nor shared. You're allow to say what you want...