How do I redirect subdomains to a different port on the same server?
Solution 1:
Solution
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]
ServerName dev.mydomain.com
ProxyPreserveHost On
# setup the proxy
<Proxy *>
Order allow,deny
Allow from all
</Proxy>
ProxyPass / http://localhost:8888/
ProxyPassReverse / http://localhost:8888/
</VirtualHost>
Solution 2:
Run the following line on terminal (specify your domain and sub domain name correctly)
sudo nano /etc/apache2/sites-available/subdomain.example.com.conf
Paste the following code and change as your requirement
<VirtualHost *:80>
ServerAdmin [email protected]
ServerName subdomain.example.com
ServerAlias subdomain.example.com
ProxyRequests Off
#ProxyPass / http://localhost:8080/
<Location />
ProxyPreserveHost On
ProxyPass http://example.com:8080/
ProxyPassReverse http://example.com:8080/
</Location>
# Uncomment the line below if your site uses SSL.
#SSLProxyEngine On
</VirtualHost>
Run the following lines on terminal (specify your domain and sub domain name correctly)
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2ensite subdomain.example.com.conf
sudo service apache2 restart
Solution 3:
Assuming that dev.mydomain.com can be resolved to mydomain.com's IP, you could add the following to your httpd.conf:
NameVirtualHost *:80
<VirtualHost *:80>
ServerName dev.mydomain.com
redirect / http://mydomain.com:8080/
</VirtualHost>
Relevant Apache documentation:
- Guide to creating name-based virtual hosts
- Core, including VirtualHost and NameVirtualHost
- 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 / http://example.com:8080/
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 ^(.*)$ http://example.com:8080$1 [R=301]
And if that's not a clear example, here's a link to a mod_rewrite beginners guide too.