Apache Redirect – Virtual Host Redirect from Subdomain to Subdirectory

apache-2.2redirect

How do I redirect requests coming to http://blog.mysite.com to http://mysite.com/blog?

Reading the apache docs on when not to use the rewrite mod, I tried a simple redirect e.g.

Redirect http://blog.mysite.com http://mysite.com/blog

But when I visit http://blog.mysite.com, it doesn't redirect me. Any suggestions?

Best Answer

Can you do a different <VirtualHost> for blog.mysite.com?

If you can, just put your Redirect config there:

<VirtualHost *:80>
    ServerName blog.mysite.com
    Redirect / http://mysite.com/blog/
</VirtualHost>

If for some reason you still need to piggy-back on the other vhost, or need to handle all subdomains and not just "blog", then use mod_rewrite:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^([^\.]+)\.mysite\.com$
RewriteRule ^/(.*)$ http://mysite.com/%1/$1 [R=301,L]