Search code examples
apachemod-rewritesubdomain

How to configure apache2 subdomains to route to different servers


I am running apache 2.4.7 and presently all my traffic is going to a backend server on 8080 on the same server/instance.

I want my www traffic to go to a new server/instance and all my other subdomains (app, api, etc.) to go to the existing 8080.

Can somebody provide some direction?

Help appreciated.

<VirtualHost *:80>
 ProxyPreserveHost On
 ServerAdmin webmaster@example.com
 ServerName example.com
 Redirect "/" "https://www.example.com/"
  RewriteEngine On
  RewriteCond %{HTTP:X-Forwarded-Proto} !https
  RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI}
 ServerAlias www.example.com
 DocumentRoot /var/www/example.com/public_html/
 Redirect "/ft/" "/"
 ErrorLog /var/www/example.com/logs/error.log
 CustomLog /var/www/example.com/logs/access.log combined
 ProxyPass / http://0.0.0.0:8080/
 ProxyPassReverse / http://0.0.0.0:8080/
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined


Solution

  • If you want to do an external redirect to the new server for the www subdomain, you'll need to add the following to your configuration, under the other rewrite rules:

    RewriteCond ${HTTP_HOST} ^www\. [NC]
    RewriteRule ^ https://www.example.com/${REQUEST_URI} [L,R=301]
    

    And you would need to remove the ServerAlias directive. This is also assuming you've already pointed DNS to the new host.


    If the new box serving the www content is to be another backed server, you would need another virtual host. Add the following at the top instead:

    <VirtualHost *:80>
        ServerName www.example.com
        ProxyPass / http://other-box/
        ProxyPassReverse / http://other-box/
    </VirtualHost>
    

    And you still would need to remove the ServerAlias directive.