Tom Senner
Tom Senner

Reputation: 111

htaccess - redirect non-www - but exclude specific subdomains

I have a system where multiple domains share one htaccess. At the Moment I redirect all non-www-requests to www using the following.

RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Only Problem is now I can't use Subdomains at all because sub-domain.myhost.com will be redirected to www.sub-domain.myhost.com.
Is there a way where the Above rule could e.g. exclude all requests starting with 'sub-'? And NOT redirect those to www.

UPDATE:

Options +FollowSymLinks -MultiViews  
RewriteEngine On  
RewriteBase /  

RewriteCond %{HTTP_HOST} ^(?!(?:sub-|www)\. [NC] 
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]  

Having only the above 5 Lines in my .htaccess will throw a "500 - Internal Server Error".

Upvotes: 1

Views: 890

Answers (1)

zx81
zx81

Reputation: 41838

Try this simple tweak:

RewriteCond %{HTTP_HOST} ^(?!(?:sub-|www)) [NC] 
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Explanation

  • The ^ anchor asserts that we are at the beginning of the string
  • The negative lookahead (?!(?:sub-|www)) asserts thatwhat follows is not sub- or www.

Upvotes: 1

Related Questions