How to prevent Drupal's .htaccess rewrite rule from redirecting mobile m._ urls to www.m._ urls

| | 2 min read

In a common secnario if a user types the url of a Drupal based website without the 'www'.prefix they will be automatically redirected to the  required site with the complete url. This is very convenient for most web users who do not want to type in the obvious 'www' prefix. Webmasters can configure this by changing the settings of the Drupal .htaccess file. However this will  be a problem if the Drupal site has a mobile version with an 'm.' prefix. Users wishing to access the mobile version of that Drupal site will inevitably be redirected to the main website.

Usually any URL of a Drupal website with/without  ‘www.’ prefix will be redirected to the site under the complete url  by the settings made in the .htaccess file. However as a side effect, this will cause the mobile URL with ‘m.’ also to be redirected in the same way which is not a good thing as we obviously need the mobile URL to be redirected to ‘m.<sitename>’, the mobile version of the website. To do that we need to make a few configuration changes in the .htacces file.

In Drupal, the most common way of redirecting all users to access the site with the 'www.' prefix, is by uncommenting  the following lines of code in the ‘.htaccess’ file.

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This will inevitably  cause all those users accessing the mobile version   m.{domain_name}.com  to get redirected to the  www.m.{domain_name}.com.

This issue can be solved by simply replacing the above mentioned lines of code with the following lines:
 

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^m\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]