Search code examples
html.htaccessurl-routing

Redirect specific host to subdirectory without affecting different hosts with .htaccess


Is it possible to redirect a specific host to a different subdirectory without affecting the other hosts that are on the same virtual domain? For example:

www.example1.com -> www.example1.com/index.html
www.example2.com -> www.example2.com/test.html

where both domains are running on the same virtual host and thus share the same .htaccess file and all other files and directories.

Thanks in advance!


Solution

  • Yes, using the .htaccess you can use the %{HTTP_HOST} to check for the URL the person is requesting. So for example:

    # http://www.example1.com => http://www.example1.com/index.html
    RewriteCond %{HTTP_HOST} ^www.example1.com [NC]
    RewriteRule ^(.*)$ /index.html
    
    # http://www.example2.com => http://www.example2.com/test.html
    RewriteCond %{HTTP_HOST} ^www.example2.com [NC]
    RewriteRule ^(.*)$ /test.html
    

    You can view these rules in action here.


    Edit: Via comments, to preven looping, you could ensure we are not requesting test.html

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^(?:www\.)?example2.be [NC]
    RewriteCond %{REQUEST_URI} !^/test.html
    RewriteRule ^(.*)$ /test.html [R,L]