Redirect port 80, 443 on Ubuntu using iptables

View more Tutorials:

Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- The Problem with Ubuntu

When you log in the Linux OS (including Ubuntu) with a user that is not "root", you can not run applications with port < 1024. Only "root" has privilege of running these applications.

So if you log in with a user that is not "root", you can not run the web application with port 80 or 443. Your website will have an unfriendly address because it has more ports on the path. For example:
  • http://yoursite.com:8080  (Address is not friendly)
  • http://yoursite.com          (Address is friendly).
In this case, you have to run the web application on a port >= 1024, for example, 8080. The user accesses to your website via port 80, and it will be redirected to port 8080. The redirection is carried out by OS, for example:
To redirect it, you need to configure iptables.

2- Configuring iptables

Firstly, you need to check application running and port used.

netstat -ntl
Tomcat is running on port 8080:
Next, run the following command to redirect port 80 traffic to port 8080

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
Run the folloing command to verify that redirect is working fine

sudo iptables -t nat -L
Next, you have to save the configuration information above to make sure that it is still useful when you restart the OS.

sudo sh -c "iptables-save > /etc/iptables.rules"

sudo apt-get install iptables-persistent
Note: If you want to remove redirecting 80 to 8080 as above, you need run the following command:

sudo iptables -t nat -D PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

View more Tutorials: