Search code examples
php.htaccess

rewrite www on the domain and non-www on the subdomain with the same htaccess file


I have website which works fine and have following in the htaccess file

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

Above gives me all urls with www prefix. Now I create version of the site for the mobile phone browsers and want to use http://m.mydomain.com/ for that version. Both domain and subdomain point to the same folder which is public_html folder. And because of the code in the htaccess file now I have http://www.m.mydomain.com/ instead of http://m.mydomain.com/ How can I keep www rewrite rule for the domain and get non-www urls for the subdomain in the same htaccess file?


Solution

  • For the specific case of your http://m.mydomain.com you could simply add another condition

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

    Now, the only time www. will be appended is if the URL doesn't already start with a www. or m.. Multiple RewriteCond lines are allowed for each RewriteRule, and all must pass for the RewriteRule to be applied.