Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excluding a subdomain from .htaccess mod_rewrite rules?

I'm not too familiar with .htaccess files, and I'm trying to exclude a subdomain (something like dev.example.com) from the following rewrite rule that's already in place:

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

This rule prohibits anyone from just entering example.com or http://example.com and forces the desired presentation of the URL, http://www.example.com.

I've tried a few options of excluding a subdomain from this rewrite rule, but to no avail. Each of the directories on the site have their own .htaccess file, but it seems this one is still taking precedence. Any ideas? Thanks!

like image 635
MindSculpt Avatar asked Dec 09 '10 16:12

MindSculpt


3 Answers

The existing rule already excludes a subdomain. You just need to append a new condition:

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

You can also get rid of regular expressions:

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

The syntax can be found at http://httpd.apache.org/docs/2.2/en/mod/mod_rewrite.html#rewritecond

like image 62
Álvaro González Avatar answered Nov 03 '22 06:11

Álvaro González


I'm not sure if this could fit for you, but it is good practice to use apache virtualhosts configuration instead of .htaccess files. In that case, for the non-www -> www redirect, I usually use something like:

<VirtualHost *:80>
    ServerName  example.com
    RedirectMatch permanent ^(.*) http://www.example.com$1
</VirtualHost>

That is generally safer than a mod_rewrite rule.

like image 23
redShadow Avatar answered Nov 03 '22 05:11

redShadow


RewriteEngine On
RewriteCond %{HTTP_HOST} !^(dev|www)\.example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
like image 34
Stephan Muller Avatar answered Nov 03 '22 05:11

Stephan Muller