Redirecting with iptables
In the last few posts we've gone over how to build and secure a reverse proxy. While this is a great option if you want to add extra access controls, rewrite urls, or hide multiple servers behind an IP, sometimes it is just a bit of overkill. Sometimes all that is needed is to change the port that a service listens on.
Let's take Atlassian Confluence for example. By default it serves up pages on port 8090. A standard HTTP request, on the other hand, is going to target port 80. In a case like this, we might only want to make Confluence listen on port 80.
The obvious solution here would be to simply update the configuration for our application, Confluence in our case, to listen on port 80. Unfortunately, what this solution has in obviousness, it lacks in correctness: unless launched by root, a program cannot open ports below 1024. So, if we have a server running as a restricted user, what recourse do we have?
My preferred solution here, and it seems to be the one shared by much of the internet1, is to simply use iptables prerouting to redirect incoming port 80 to our port of choice. This is actually a rather simple task for us: we'll only need three lines. We'll sudo to root, add a firewall redirect rule, and then save the rules to /etc/iptables/rules.v4.
sudo su iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8090 apt-get install iptables-persistent
Out of curiosity, I searched “Running a web server on port 80 on linux”. Three of the top four results were this same solution. ↩︎
In the event that we ever do need to move to a reverse proxy, we can remove our forwarding rule by removing the line -A PREROUTING -p tcp -m tcp –dport 80 -j REDIRECT –to-ports 8090 from /etc/iptables/rules.v4. ↩︎
That can be read as “Add a rule to the prerouting chain in the nat table. It should redirect any tcp traffic with a destination of port 80 to port 8090.” ↩︎