How to Build a Simple Website Firewall with iptables on Linux
This step‑by‑step guide shows how to install iptables, clear existing rules, set default DROP policies, allow established connections and loopback traffic, block a specific IP from accessing port 80, save the configuration, and verify that the firewall works as intended.
Step 1: Verify iptables Installation
Check whether iptables is already present by running: sudo iptables -V If the command returns version information, iptables is installed; otherwise install it with:
sudo apt-get update
sudo apt-get install iptablesStep 2: Flush Existing Rules
Before adding new rules, clear all current firewall rules to avoid conflicts:
sudo iptables -F
sudo iptables -X
sudo iptables -Z
sudo iptables -t nat -FStep 3: Set Default Policies
Define the default action for unmatched traffic. The example sets both INPUT and FORWARD chains to DROP:
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROPStep 4: Allow Established Connections
Permit traffic for connections that are already established or related to an existing connection:
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPTStep 5: Allow Loopback Interface
Ensure the local loopback interface (lo) can communicate without restriction:
sudo iptables -A INPUT -i lo -j ACCEPTStep 6: Block a Specific IP from Accessing HTTP
To reject HTTP requests (port 80) from a particular IP address (e.g., 192.168.0.100), add the following rule:
sudo iptables -A INPUT -s 192.168.0.100 -p tcp --dport 80 -j REJECTThis stops all TCP traffic destined for port 80 from that IP.
Step 7: Save and Apply the Rules
Persist the current rule set to a file:
sudo sh -c "iptables-save > /etc/iptables.rules"Later, restore the saved rules with:
sudo iptables-restore < /etc/iptables.rulesStep 8: Verify the Configuration
Test the firewall by attempting to access the website from the blocked IP address; the request should be rejected, confirming that the rule works as expected.
By following these steps, you can create a basic yet effective website firewall on Linux using iptables, tailoring the rule set to your specific security requirements.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
