So I'm trying to write a mod_rewrite rule that will send everything on my main domain to a subdomain.

For example, redirect




Here's what I have so far:

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

But it doesn't seem to working. Any tips?


I think you're missing something in your RewriteCond line. Try this:

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

So add the %{HTTP_HOST} into your RewriteCond rule... Note that I haven't tested this, so please post the results...

| improve this answer | |
  • Doesn't the dot for .com in the RewriteCond need escaping? – user145545 Nov 6 '16 at 5:13
  • In its current state this won't do anything. The HTTP_HOST server variable contains just the hostname (whatever is in the Host HTTP request header) - it does not contain the protocol (http://), or part of the URL-path (the trailing slash in the above example). The OP also uses the domain apex in the example URL, whereas this specifically checks for the www subdomain. And yes, the second dot before the TLD does ideally need escaping (although unlikely to cause a problem if not). So, the condition should be written like: RewriteCond %{HTTP_HOST} ^(www\.)?example\.com [NC] – MrWhite Aug 29 '18 at 15:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.