This will describe how to create persistent rules to forward the HTTP/S ports on a local server.
There is a couple of ways to make the port forward rules persistent correctly. With “correctly” I mean that the implementation follows the network (interface) service instead of a crontab
or rc.local
that only runs on a reboot.
This example should be generic enough to work on any modern Linux distribution that’s not otherwise configured with exotic firewall settings and rules. Those setting up their own FW will probably not need this guide anyhow
Do everything as root or use sudo. This guide assumes no rules are previously set/active.
Create the rules via the CLI:
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 9443
Create an empty file that will hold the rules:
touch /etc/iptables.blynk.rules
Create a script that will run when the network is connected called iptables. Once the network is up, the rules saved in iptables.blynk.rules
will be restored with the command iptables-restore (kinda self-explanatory). Make the file executable:
echo '#!/bin/sh' > /etc/network/if-up.d/iptables
echo "iptables-restore < /etc/iptables.blynk.rules" >> /etc/network/if-up.d/iptables
chmod +x /etc/network/if-up.d/iptables
Create a similar script that saves the current rules when the network disconnects:
echo '#!/bin/sh' > /etc/network/if-down.d/iptables
echo "iptables-save > /etc/iptables.blynk.rules" >> /etc/network/if-down.d/iptables
chmod +x /etc/network/if-down.d/iptables
To save the rules to iptables.blynk.rules
, just restart the network service (or reboot the computer):
service networking restart
The file should now be populated and look something like this:
# Generated by iptables-save v1.6.0 on Tue Jan 23 01:00:00 2018
*nat
:PREROUTING ACCEPT [1:36]
:INPUT ACCEPT [1:36]
:OUTPUT ACCEPT [1:76]
:POSTROUTING ACCEPT [1:76]
-A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080
-A PREROUTING -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 9443
COMMIT
# Completed on Tue Jan 23 01:00:00 2018
Check that the rules are applied with iptables -L -t nat
Chain PREROUTING (policy ACCEPT)
target prot opt source destination
REDIRECT tcp -- anywhere anywhere tcp dpt:http redir ports 8080
REDIRECT tcp -- anywhere anywhere tcp dpt:https redir ports 9443
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
Chain POSTROUTING (policy ACCEPT)
target prot opt source destination
That’s it!
If you run the Blynk server with root privileges, change the settings in server.properties
so it will listen on the default ports for HTTP/S instead and forget everything I said about iptables
#http and web sockets port
http.port=80
#https and web sockets port
https.port=443
I see no reason for this to not work on Raspbian, but I haven’t tested it!