Map a sub domain to localhost:port with httpd
This post will show you how to link a sub domain to an application running on your server at a certain port.
First you will have to find your httpd config folder (usually /etc/httpd/config.d/
). Add the following snippet to the vhost.conf
file. It you are doing it the Debian way, you will need to create a file containing the following snippet in the sites-available
directory of /etc/apache2/
(see this explanation on ServerFault)
Let’s look at what this sniped actually does:
ServerName
Sets the hostname the server uses to identify itself.
It will be used as theHost
in the HTTP header. More information can be found in the httpd documentation on Name-based Virtual hosts.ProxyPass {path} {URL}
Sets up a link from the virtual path{path}
to the server listening at{URL}
.
In our case we want to redirect the entire sub domain, so we choose/
as our virtual path. Since our server is running locally at a port that should not be accessible externally, our taget URL islocalhost:1337/
with1337
the port number your application is running on. Note that the{URL}
is a relative address from the servers’ perspective and ends with a/
.ProxyPassReverse {path} {URL}
makes sure httpd converts theLocation
,Content-Location
andURI
headers on HTTP redirect responses are correct. Thus, a redirect toLocation: localhost:1337/foo
will becomeLocation: sub.beardhatcode.be/foo
.ProxyRequests off
Prohibit the use of your server as a real proxy Server. This is the default value, but we set it just to be sureErrorLog
andCustomLog
are the httpd log files for the sub domain. It’s always good to make a log file for each sub domain. Note that these only contain httpd errors. Errors of your application will be stored elsewhere depending on the application.
Don’t forget to restart httpd after saving the changes.
Bonus
If the server refuses connection, your servers firewall may be blocking the connection to localhost:port
. Issue the following command as root. Try it out without the -P
first, if it works add the -P
to make the change persist even when the system is rebooted.
Some applications (such as Jenkins) require that you use ProxyPass {path} {URL} nocanon
and AllowEncodedSlashes NoDecode
. This will give the application you are running at localhost the exact URL the user entered rather than the canonicalized rewritten version.
If you want to use a directory rather than a sub domain to map your application to, use
and modify the settings of your application so that it knows it’s running in a directory.
#References