Friday, January 28, 2011

mod_rewrite: redirect from subdomain to main domain

I have two domains - domain.com and forum.domain.com that points to the same directory.

I'd like redirect all request from forum.domain.com to domain.com (for example: forum.domain.com/foo to domain.com/forum/foo) without changing address in addres bar (hidden redirect).

I wrote something like this and put it into .htaccess file:

Options +FollowSymlinks
RewriteEngine on   

RewriteCond %{HTTP_HOST} ^forum\.example\.net$
RewriteRule (.*) http://example.com/forum/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-s [NC]
RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteRule ^(.+) index.php/$1 [L]

That works only if I add Redirect directive:

RewriteRule (.*) http://example.com/forum/$1 [R,L]

But it changes previous address in address bar.

EDIT:

Ok, let's make it simple. I added those two lines at the end of the c:\windows\system32\drivers\etc\hosts on my local computer:

127.0.0.3   foo.net
127.0.0.3   forum.foo.net

Now, I created two virtual hosts:

<VirtualHost foo.net:80>
    ServerAdmin admin@admin.com
    ServerName foo.net
DocumentRoot "C:/usr/src/foo"
</VirtualHost>

<VirtualHost forum.foo.net:80>
    ServerAdmin admin@admin.com
    ServerName forum.foo.net
DocumentRoot "C:/usr/src/foo"
</VirtualHost>

..and directory called "foo", where i put two files: .htaccess and index.php.

Index.php:

<?php

echo $_SERVER['PATH_INFO'];
?>

.htaccess:

Options +FollowSymlinks
RewriteEngine on
RewriteBase /

RewriteCond %{HTTP_HOST} ^forum\.foo\.net$
RewriteCond %{REQUEST_URI} !^/forum/
RewriteCond %{REQUEST_FILENAME} !-s [NC]
RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteRule ^(.+)$ /index.php/forum/$1 [L]

RewriteCond %{HTTP_HOST} !^forum\.foo\.net$
RewriteCond %{REQUEST_FILENAME} !-s [NC]
RewriteCond %{REQUEST_FILENAME} !-d [NC]
RewriteRule ^(.+) index.php/$1 [L]

When I type address http://forum.foo.net/test in address bar, it displays /forum/test which is good. http://foo.net/a/b/c shows /a/b/c which is good. But! http://forum.foo.net/ displays empty value (should display /forum).

  • Enable mod_proxy and use the P flag instead.

    Bald : Hmm, does not work. Could you give me an example?
    Ignacio Vazquez-Abrams : `RewriteCond %{HTTP_HOST} ^forum\.example\.net$` `RewriteRule (.*) http://example.com/forum/$1 [L,P]`

0 comments:

Post a Comment