Skip to main content

Configuring iptables

You can configure IPTables to restrict access to a particular server by IP address.

Unless you save the configuration for permanent use via the iptables-save command, your configuration will not persist between server restarts. 

Be sure your configuration is correct before considering a permanent configuration save - you could lock yourself out of your own server!

For the most part, IPTables is most useful on test environments where you only want a handful of IPs to have access. In any other case, whitelisting IPs via your WAF configuration is better practice.

Example IPLIST file
One IP address per line, no spaces, no new line at end of file. Remove all other text, including this line.
1.2.3.4
5.6.7.8
Example bash script for updating iptables configuration

If you need to empty the existing iptables rules, use this command to flush the configuration and remove all added rules:

sudo iptables -F

The script below then adds all IP addresses in the "IPLIST" file you created above. You will need to be using the root user to run this script correctly.

#!/bin/bash

while IPS=: read -r ip; do
# Allow all IPs that are in the IPLIST file to reach this server.
# Only on ports 80 and 443 (HTTP and HTTPS).
iptables -I INPUT -p tcp --dport 80 -s $ip -j ACCEPT
iptables -I INPUT -p tcp --dport 443 -s $ip -j ACCEPT
done < "./IPLIST"

# Allow localhost connections (SSH tunnels won't work otherwise.)
iptables -I INPUT -i lo -j ACCEPT

# Reject any other connections to ports 80 and 443.
iptables -A INPUT -p tcp --dport 80 -j REJECT
iptables -A INPUT -p tcp --dport 443 -j REJECT

exit 1