How to rewrite domainA to domainB using htaccess Apache Proxy Module and RewriteRule

How to rewrite domainA to domainB using htaccess Apache Proxy Module and RewriteRule

Mod proxy is a powerful Apache modules and provides URL rewriting and domain mapping capabilities. With proxy module enabled on apache server you can rewrite your domain URLs to an external domain that is being hosted on a diffrent web server. Proxy module allows you to use P flag (Proxy) in RewriteRule directive to rewrite URLs from one server to the other.

Apache mod proxy RewriteRule in htaccess

References :

How do you enable proxy module?

In order to use mod-Proxy,you need to enable proxy module on your apache server. To enable the module type the following commands in your terminal window :

  • Install mod proxy using the following command
    sudo a2enmod proxy
  • Restart your server

    sudo /etc/init.d/apache2 restart

    or

    sudo /etc/init.d/apache2 restart

After enabling proxy module ,you can use mod rewrite [P] flag in your htaccess file to map your domain.
The following is a basic mod rewrite example to rewrite Domain A to Domain B.

RewriteEngine On
RewriteRule (.*) http://example2.com/$1 [P]

The rewrite rule example above maps a domain to another domain using the P (Proxy module) . Any request to domain A will be served by Domain B without changing the URL in browser address bar.

ProxyPass directive

ProxyPass is a directive of proxy module and can be used in server.config file to proxy requests between two domains. ProxyPass is faster then using P flag in a RewriteRule. The following example rewrites DomainA/foo to DomainB/bar . You will get the contents from domainB by going to domainA URL in browser.

ProxyPass “/foo” “http://domainB.com/bar”

You can also use ProxyPass directive inside Location directive to map a specific dirctory Path

<Location “/thisDir/foo”>
ProxyPass “http://domainB.com/bar”
</Location>

ProxyPass insde Location directive will only apply to the path specified in Location. If The example code above is placed in server.config file in domainA this will rewrite domainA.com/thisDir/foo to domainB.com/bar .
You can also use a regular expressions based pattern in ProxyPassMatch directive.

ProxyPassMatch “^/foo$” “http://domainB.com/bar”

Using proxy module in htaccess RewriteRule

If you don’t have access to your main server.config file then you can use RewriteRule in your htaccess. P flag is used to map requests between two domains.

RewriteEngine on
RewriteRule ^foo$ https://domainB.com/bar [P]

This will internally map /foo to /domainB.com/bar just like a normal rewrite rule you use to rewrite your domain URLs.

Leave a Reply

Your email address will not be published. Required fields are marked *