Port re-direction

Updated on 28 Dec 2018

Introduction

Many of the applications that I install are accessed via the web thru a port other than port 80. It means accessing it might look something like this:

http://localhost:8080

What would be nice is if I could have some sort of redirect like this:

  • http://localhost/jenkins -> http://localhost:8080

So that I can navigate to the web-application in a way that makes sense for me, and apache somehow transforms it into what the application needs.

Enable proxy

There are several modules that need to be enabled.

sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod headers

And once they have been enabled, we will need to restart apache.

sudo systemctl restart apache2

Modify site config file

Towards the end of the <VirtualHost *:80> tag, add the following lines.

ProxyRequests     Off
ProxyPreserveHost On
AllowEncodedSlashes NoDecode

# if I have :8080/jenkins/ (forward slash after jenkins) then I get a 403 error
# about not valid breadcrumb.
ProxyPass         /jenkins http://localhost:8080/jenkins nocanon
ProxyPassReverse /jenkins http://localhost:8080/jenkins

Being careful not to add trailing spaces otherwise you’ll get the errors described above.

This means that when you navigate to https://servername/jenkins Apache will forward the request to http://localhost:8080/jenkins where you guessed it, it will be picked up by the Jenkins service.

Important: In order for this to work, the prefix must be the same on Apache and Jenkins. I.e.

  • ProxyPass /jenkins http://localhost:8080/jenkins (works)
  • ProxyPass /jenkins http://localhost:8080 (will not work)
  • ProxyPass / http://localhost:8080/jenkins (will not work)
  • ProxyPass / http://localhost:8080 (works)

Modify /etc/default/jenkins

Since we are using the jenkins prefix, we must add that to the jenkins configuration file.

The default jenkins setup will already have this predefined in the file

NAME=jenkins

...

PREFIX=/$NAME

All we need to do is add the prefix to JENKINS_ARGS as shown below.

JENKINS_ARGS="--webroot=/var/cache/$NAME/war --httpPort=$HTTP_PORT --prefix=$PREFIX"

Restart the services

Modifications to Jenkins and Apache2 require that they both need to be restarted.

sudo systemctl restart jenkins
sudo systemctl restart apache2

Testing

Now we can navigate to the following url

https://servername/jenkins

And we will see that we can access Jenkins using port forwarding.