1

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

For example, redirect

http://example.com/1/2/3/4/5?n=6&i=7

to

http://sub.example.com/1/2/3/4/5?n=6&i=7

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?

MrWhite
  • 11,643
  • 4
  • 25
  • 40
  • 1
    possible duplicate of [Everything You Ever Wanted to Know about Mod_Rewrite Rules but Were Afraid to Ask?](http://serverfault.com/questions/214512/everything-you-ever-wanted-to-know-about-mod-rewrite-rules-but-were-afraid-to-ask) – Shane Madden May 23 '11 at 02:32
  • @Shane Madden - don't think it's a dupe myself. That linked q is very helpful, but since it doesn't cover this specific question I think it is useful in its own right. – Gavin C May 23 '11 at 22:24
  • 1
    @Gavin Fair point. That question could use a wider breadth of examples, it's a little heavy on referrer examples at the moment. – Shane Madden May 24 '11 at 00:46
  • Try adding the following to `.htaccess` in the parent directory above the directory of interest: `RedirectMatch ^/foo/$ /foo/bar/` or `RedirectMatch ^/foo/$ /bar/baz/`. Also see [How to get apache2 to redirect to a subdirectory](http://serverfault.com/q/9992/145545). –  Nov 06 '16 at 08:26

1 Answers1

3

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...

dotmike
  • 73
  • 7
  • Doesn't the dot for `.com` in the RewriteCond need escaping? –  Nov 06 '16 at 05: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