2nrds.com
we dig technology
Home
- The topics
Suggest an article
Have a good idea for an article? Something you want to know? Suggest an idea for an article and we just might write one for you.Port forwarding in Linux
In Linux (and most other *nix systems) ports 1-1024 are called “privileged ports”. That means that only root processes can listen and serve on those ports.
It is not always the best idea to run web server like Apache as root. Also many Java web servers such as Tomcat and application servers like JBoss and Glassfish run as default on port 8080.
I suggest here running various web servers in non-privileged ports (higher than 1024) as non root user – specially Java web servers.
It is assumed that your web server listens http traffic at port 8080 and port 8443 is used for SSL protected (https) traffic.
This is how you can forward all traffic from external port 80 to port 8080 and all traffic from port 443 to 8443.
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080
iptables -t nat -A PREROUTING -p udp -m udp --dport 80 -j REDIRECT --to-ports 8080
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 8443
iptables -t nat -A PREROUTING -p udp -m udp --dport 443 -j REDIRECT --to-ports 8443
Save the script above for example to text file “my_portforward” and load it to iptables by running command:
source my_portforward
You should have now working port forward from port 80 to port 8080 and from port 443 to 8443. If you have web server process running at port 8080 you should see the page with your favorite internet browser by pointing to your web server.
Notice that you do not see nat with command
iptables -L
Easiest way to see that you really successfully loaded redirect is to use command:
iptables-save | grep PREROUTING
Command iptables-save is also the command you need to make your firewall start automatically when you boot your computer.
How to make the firewall start at boot
First make /etc/iptables folder and your current active firewall rule there:
mkdir /etc/iptables
iptables-save > /etc/iptables/firewall
Then make script to load your firewall rules and save it to location
/etc/network/if-up.d/firewall
#!/bin/sh
iptables-restore < /etc/iptables/firewall
And check that script rights allow running it (as root or with sudo)
chmod 700 /etc/network/if-up.d/iptables







Hi!
chmod 700 /etc/network/if-up.d/iptables
Or
chmod 700 /etc/network/if-up.d/firewall
Alien · Mar 3, 02:25 PM
Hi,
How can I restore to state before executing port forwarding as your solution?
Thanks
Khanh · May 4, 12:10 AM