How do I redirect subdomains to a different port on the same server?

Solution 1:


Here is what I finally came up with after being set in the right direction by Miles Erickson. I wanted the address bar to reflect the original subdomain/domain of the request and not the redirected server and port, but he put me on the right path to Google up a solution using VirtualHost and I finally found a solution that included the use of mod_proxy.

<VirtualHost *:80>
    ServerAdmin [email protected]
    ProxyPreserveHost On

    # setup the proxy
    <Proxy *>
        Order allow,deny
        Allow from all
    ProxyPass / http://localhost:8888/
    ProxyPassReverse / http://localhost:8888/

Solution 2:

Run the following line on terminal (specify your domain and sub domain name correctly)

sudo nano /etc/apache2/sites-available/ 

Paste the following code and change as your requirement

<VirtualHost *:80>
        ServerAdmin [email protected]
        ProxyRequests Off

        #ProxyPass / http://localhost:8080/
        <Location />
                ProxyPreserveHost On
     # Uncomment the line below if your site uses SSL.
     #SSLProxyEngine On

Run the following lines on terminal (specify your domain and sub domain name correctly)

sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2ensite
sudo service apache2 restart

Solution 3:

Assuming that can be resolved to's IP, you could add the following to your httpd.conf:

NameVirtualHost *:80

<VirtualHost *:80>
    redirect /

Relevant Apache documentation:

  1. Guide to creating name-based virtual hosts
  2. Core, including VirtualHost and NameVirtualHost
  3. Redirect

Related question: Apache redirect based on hostname

(Note: the original version of this answer incorrectly suggested the use of RedirectMatch, which, as @ChrisS helpfully pointed out, cannot parse the domain portion of the URL.)

Solution 4:

Add in your main vhost configuration the following lines:

ProxyPreserveHost On
ProxyPass /
ProxyPassReverse / http://example:8080/

Note that this requires mod_proxy on Apache.

Solution 5:

You're looking for mod_rewrite. Here's the link to Apache's documentation which includes many examples for basic and advanced configurations..

And if you're unable to interpret the documentation yourself, try adding this to httpd.conf:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^dev\.example\.com$ [NC]        
RewriteRule ^(.*)$$1 [R=301]    

And if that's not a clear example, here's a link to a mod_rewrite beginners guide too.