Forward HTTP Port 80 to 8000 on localhost
Using iptables
you can easily forward port 80 to another port (8000 in this example) so that you can run web servers as a non-root user. Requests will be forward/proxied transparently without HTTP redirects.
Note: This means any user on your machine can host something on port 80 without explicit permission.
Run these commands to forward port 80 to 8000 (change the ports as needed):
sudo iptables -I INPUT 1 -p tcp --dport 8000 -j ACCEPT
sudo iptables -I INPUT 1 -p tcp --dport 80 -j ACCEPT
sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8000
sudo iptables -t nat -I OUTPUT -p tcp -d 127.0.0.1 --dport 80 -j REDIRECT --to-ports 8000
Now, http://localhost/
will resolve to http://localhost:8000/
.
If you need to test SSL, you can also forward port 443 to 8443:
sudo iptables -I INPUT 1 -p tcp --dport 8443 -j ACCEPT
sudo iptables -I INPUT 1 -p tcp --dport 443 -j ACCEPT
sudo iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8443
sudo iptables -t nat -I OUTPUT -p tcp -d 127.0.0.1 --dport 443 -j REDIRECT --to-ports 8443
Now, https://localhost/
will resolve to https://localhost:8443/
These settings will be lost upon reboot. On Ubuntu (and Debian), you can easily save them permanently by installing the iptables-persistent
package:
sudo apt-get install iptables-persistent
Upon installing, your current forwarding rules will be saved. If you want to save them again later:
sudo dpkg-reconfigure iptables-persistent