1

NOTE: Using <VirtualHost> parameter only.

How do I redirect a directory (say example.com/groups/) to a sub-domain (say groups.example.com), and also the www of that sub-domain (www.groups.example.com) to the non-www URL of that sub-domain (groups.example.com)?


Precisely (⇒ stands for 'should 301 redirect to'):

example.com/groups/groups.example.com

www.groups.example.comgroups.example.com


I have read that using <VirtualHost> is better than all those redirection rules that are usually used (i.e. that using redirection engine is pretty heavy on disk i/o). So, I would like to have the above problem solved using <VirtualHost> in .htaccess / httpd.conf if possible. Thanks!

Community
  • 1
  • 1
its_me
  • 10,998
  • 25
  • 82
  • 130

1 Answers1

1

Something like this should work

<VirtualHost *:80>
    ServerName example.com 
    ServerAlias groups.example.com www.groups.example.com

    RewriteEngine on
    # example.com/groups/ -> groups.example.com
    RewriteCond %{SERVER_NAME}  ^example\.com$
    RewriteRule ^/(\w+)/?$  http://$1.example.com [R=301,L]

    # www.groups.example.com -> groups.example.com
    RewriteCond %{SERVER_NAME}  ^www\.(\w+)\.example\.com$
    RewriteRule ^/(.*)$ http://%1.example.com/$1 [R=301,L]
</VirtualHost>

or specifically for groups

<VirtualHost *:80>
    ServerName example.com 
    ServerAlias groups.example.com www.groups.example.com

    RewriteEngine on
    # example.com/groups/ -> groups.example.com
    RewriteCond %{SERVER_NAME}  ^example\.com$
    RewriteRule ^/groups/?$  http://groups.example.com [R=301,L]

    # www.groups.example.com -> groups.example.com
    RewriteCond %{SERVER_NAME}  ^www\.groups\.example\.com$
    RewriteRule ^/(.*)$ http://groups.example.com/$1 [R=301,L]
</VirtualHost>
nikoshr
  • 32,926
  • 33
  • 91
  • 105
  • It doesn't work because you are missing the directory (/groups/) in the second line. Can you please correct it? **EDIT:** Something's wrong. It doesn't work even after making that correction. – its_me Mar 16 '12 at 13:19
  • Tested both on my server, they work. Maybe you didn't add RewriteEngine on before those lines? Modified my answer to reflect a sample httpd configuration – nikoshr Mar 16 '12 at 13:59