Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect directory to another domain with Apache?

I have an Apache server with two domains (via VirtualHost) on it.
The file setup is like this: /example1/example2/
example1 is the root for www.example1.com
example2 is the root for www.example2.com
I would like for www.example1.com/example2/<whatever else> to redirect to www.example2.com/<whatever else>
I have access to the main Apache configuration file. Any tips on how to do this? I'm not very familiar with configuring Apache, so any explanations would be very much appreciated.

The other questions related to this one lacked explanations, so I felt I had to post my own question.

like image 881
Yoshiyahu Avatar asked Oct 22 '25 09:10

Yoshiyahu


1 Answers

You can use an .htaccess file to do this pretty quickly. In www.example1.com/example2/, you would create this .htaccess file.

<VirtualHost *:80>
    ...
    <Directory /path/to/vhost/>
      RewriteEngine on
      RewriteBase /example2/
      RewriteRule ^(.*)$ http://www.example2.com/$1 [R=301]
    </Directory>
</VirtualHost>

This does assume that you want the redirect to be a 301, and that the example2 folder has AllowOverride All set.

This rule works using regex to capture the incoming URL, sans the example2 bit, then appending it to the rewritten URL. The R in the square brackets tells Apache to use a Location header to the rewritten URL. The =301 tells Apache to use a 301 Permanent Redirect header.

like image 147
Chris Henry Avatar answered Oct 25 '25 02:10

Chris Henry