Tutorials

Basic Firewall Configuration for Linux Web Servers

Administrator
By Administrator
Published Oct 03, 2025
8 min read
Basic Firewall Configuration for Linux Web Servers

Basic Firewall Configuration for Linux Web Servers

Your web server is like a house in a busy neighborhood. Without doors and locks, anyone could walk right in. Firewalls are those essential security measures that keep unwanted visitors out while allowing legitimate traffic to reach your services.

I learned this lesson the hard way when I first started hosting websites. I had a beautiful WordPress site running smoothly, thinking everything was secure. One morning, I woke up to find my server had been compromised, hosting malicious content and sending spam emails. The culprit? I'd never configured a firewall, leaving my server completely exposed to the internet.

That incident taught me that firewall configuration isn't optional—it's fundamental. In this guide, I'll show you how to properly configure a firewall for your Linux web server, covering both simple and advanced configurations that will keep your server secure while ensuring your websites remain accessible.

Let's build your digital fortress! 🛡️

Understanding Firewalls: The Basics

A firewall is a network security system that monitors and controls incoming and outgoing network traffic based on predetermined security rules. Think of it as a security guard for your server, checking every request and deciding whether to allow or block it.

Key concepts:

  • Inbound traffic: Connections coming into your server
  • Outbound traffic: Connections going out from your server
  • Ports: Logical endpoints for different types of traffic (HTTP = port 80, HTTPS = port 443, SSH = port 22)
  • Protocols: TCP, UDP, ICMP - different ways data travels

Choosing Your Firewall Tool

Linux offers several firewall solutions. For web servers, we'll focus on two main options:

UFW (Uncomplicated Firewall) - Beginner-friendly interface - Perfect for most web server scenarios - Built on top of iptables

iptables - More powerful and flexible - Steeper learning curve - Better for complex configurations

For this guide, we'll start with UFW since it's perfect for most web server setups, and then cover iptables basics for advanced users.

Getting Started with UFW

UFW (Uncomplicated Firewall) is Ubuntu's default firewall tool. It's designed to be easy to use while providing excellent security for most scenarios.

Installing UFW

UFW comes pre-installed on Ubuntu, but if it's not available:

sudo apt update
sudo apt install ufw -y

Checking UFW Status

sudo ufw status

You should see "Status: inactive" if it's not enabled yet.

Setting Default Policies

Before adding rules, set up default policies. The best practice is to deny all incoming traffic and allow all outgoing traffic:

sudo ufw default deny incoming
sudo ufw default allow outgoing

This approach is called "default deny" - we block everything by default, then explicitly allow only the traffic we need.

Essential Rules for Web Servers

Let's add the essential rules your web server needs to function properly.

Allow SSH Access

CRITICAL: Always allow SSH first, or you could lock yourself out of your server!

sudo ufw allow ssh

Or specify the port directly:

sudo ufw allow 22/tcp
Allow HTTP and HTTPS Traffic

Enable web traffic so visitors can access your websites:

sudo ufw allow http
sudo ufw allow https

Or use the application profiles:

sudo ufw allow 'Nginx Full'
sudo ufw allow 'Apache Full'
Allow FTP (if needed)
sudo ufw allow ftp

Advanced UFW Rules

Rate Limiting for SSH

Protect against brute force attacks by limiting SSH connections:

sudo ufw limit ssh

This allows up to 6 connections in 30 seconds, then blocks additional attempts.

Allow Specific IP Addresses

Allow access only from specific IP addresses (great for admin panels):

sudo ufw allow from 192.168.1.100
sudo ufw allow from 203.0.113.1 to any port 22
Allow Port Ranges

Some applications need ranges of ports:

sudo ufw allow 6000:6007/tcp
sudo ufw allow 6000:6007/udp

Enabling the Firewall

Once you're confident in your rules, enable UFW:

sudo ufw enable

Type 'y' when prompted. Your firewall is now active!

Managing UFW Rules

View Current Rules
sudo ufw status numbered
sudo ufw status verbose
Delete Rules

Delete by rule number:

sudo ufw delete 2

Delete by specification:

sudo ufw delete allow http
Insert Rules at Specific Positions
sudo ufw insert 1 allow from 192.168.1.100

Introduction to iptables

While UFW is great for most scenarios, understanding iptables gives you more control and helps in complex situations.

Basic iptables Concepts

iptables uses different "chains" to process packets:

  • INPUT: Incoming packets
  • OUTPUT: Outgoing packets
  • FORWARD: Packets being routed through the server

Essential iptables Commands

View Current Rules
sudo iptables -L -v -n
Allow Established Connections
sudo iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
Allow Loopback Interface
sudo iptables -A INPUT -i lo -j ACCEPT
Allow SSH, HTTP, HTTPS
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
Set Default Policy to Drop
sudo iptables -P INPUT DROP

Saving iptables Rules

iptables rules don't persist after reboot. Install iptables-persistent:

sudo apt install iptables-persistent -y

Save current rules:

sudo netfilter-persistent save
sudo netfilter-persistent reload

Advanced Firewall Configurations

Protecting Against DDoS Attacks

Limit Connections per IP
# Allow max 50 connections per IP
sudo iptables -A INPUT -p tcp --dport 80 -m connlimit --connlimit-above 50 -j DROP
Rate Limit New Connections
# Allow max 20 new connections per minute
sudo iptables -A INPUT -p tcp --dport 80 -m conntrack --ctstate NEW -m limit --limit 20/min --limit-burst 30 -j ACCEPT

Port Knocking (Advanced Security)

Port knocking is like a secret knock to access your server. You "knock" on specific ports in sequence, and only then does the server open the port you actually want to access.

Set Up Port Knocking
# Install knockd
sudo apt install knockd -y

# Configure knockd
sudo nano /etc/knockd.conf

Add this configuration:

[options]
        UseSyslog

[openSSH]
        sequence    = 7000,8000,9000
        seq_timeout = 5
        command     = /sbin/iptables -A INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
        tcpflags    = syn

[closeSSH]
        sequence    = 9000,8000,7000
        seq_timeout = 5
        command     = /sbin/iptables -D INPUT -s %IP% -p tcp --dport 22 -j ACCEPT
        tcpflags    = syn

Start the service:

sudo systemctl start knockd
sudo systemctl enable knockd

To access SSH, you would "knock" on the ports:

knock -v your_server_ip 7000 8000 9000

Firewall for Different Server Types

Web Server Configuration

Basic web server rules:

# UFW commands for a typical web server
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https
sudo ufw limit ssh
sudo ufw enable

Database Server Configuration

If you're running a separate database server:

# Allow only specific application servers
sudo ufw allow from 192.168.1.10 to any port 3306  # MySQL
sudo ufw allow from 192.168.1.10 to any port 5432  # PostgreSQL

Mail Server Configuration

For mail servers, you'll need additional ports:

sudo ufw allow smtp
sudo ufw allow submission
sudo ufw allow imaps
sudo ufw allow pop3s

Monitoring and Logging

Enable Firewall Logging

# UFW logging
sudo ufw logging on

# Log specific denied connections
sudo ufw deny log-all from any to any

Monitor Firewall Logs

# View UFW logs
sudo tail -f /var/log/ufw.log

# View kernel logs (iptables)
sudo tail -f /var/log/kern.log

Block Suspicious IPs Automatically

Create a simple script to block IPs with too many failed attempts:

#!/bin/bash
# block-suspicious-ips.sh

# Block IPs with more than 50 failed SSH attempts
grep "Failed password" /var/log/auth.log | grep -oP '\d+\.\d+\.\d+\.\d+' | sort | uniq -c | sort -nr | awk '$1 > 50 {print "sudo ufw deny from "$2}' > /tmp/bad_ips.txt

while read -r line; do
    eval $line
done < /tmp/bad_ips.txt

Security Best Practices

Regular Maintenance

  • Review rules regularly - remove unnecessary opened ports
  • Update firewall rules when changing server configuration
  • Monitor logs for suspicious activity
  • Test rules in staging before production

Common Mistakes to Avoid

  • ❌ Forgetting to allow SSH before enabling the firewall
  • ❌ Opening too many ports - only what's necessary
  • ❌ Not logging denied connections - makes troubleshooting harder
  • ❌ Ignoring firewall logs - missing potential security issues
  • ❌ Using default passwords with firewall protection

Performance Considerations

  • Keep rules simple - complex rules slow down processing
  • Use UFW profiles when possible
  • Order rules efficiently - frequently matched rules first
  • Monitor CPU usage of firewall processing

Testing Your Firewall

Port Scanning

Use nmap to test which ports are open:

# Install nmap
sudo apt install nmap -y

# Scan your server
nmap your_server_ip

# Comprehensive scan
nmap -sS -sV -O your_server_ip

Connection Testing

Test different services:

# Test SSH
ssh -v your_server_ip

# Test HTTP
curl -I http://your_server_ip

# Test HTTPS
curl -I https://your_server_ip

Disaster Recovery

If you accidentally lock yourself out, most VPS providers offer console access through their web panel. Use this to:

# Disable firewall if needed
sudo ufw disable

# Or reset rules to default
sudo ufw reset

Final Thoughts

Firewall configuration isn't just about security—it's about peace of mind. A properly configured firewall is your first line of defense against countless automated attacks that target vulnerable servers every minute of every day.

Remember these key principles:

  • Default deny - block everything, allow only what you need
  • Least privilege - open only necessary ports
  • Regular monitoring - watch your logs for suspicious activity
  • Keep it simple - complex rules are hard to maintain

Start with UFW for simplicity, and explore iptables as you become more comfortable. The most important thing is to have some form of firewall protection enabled on every server you manage.

Your server is an investment in your digital presence. A firewall is the insurance that protects that investment. Configure it once, configure it right, and sleep better knowing your server is secure. 🛡️

Happy securing! Your server will thank you for it.

Related Articles

How to Backup and Restore a Website on VPS Linux

How to Backup and Restore a Website on VPS Linux

Oct 03, 2025

How to Backup and Restore a Website on VPS Linux That moment when you realize your website is gon...

Setting Up Load Balancing with Nginx for High Traffic Sites

Setting Up Load Balancing with Nginx for High Traffic Sites

Oct 03, 2025

Setting Up Load Balancing with Nginx for High Traffic Sites Your website is growing. Traffic is i...

How to Monitor Server Resources with htop and netstat

How to Monitor Server Resources with htop and netstat

Oct 03, 2025

How to Monitor Server Resources with htop and netstat Ever wonder why your website suddenly slows...

How to Add a New Domain to Your Nginx Server

How to Add a New Domain to Your Nginx Server

Oct 03, 2025

How to Add a New Domain to Your Nginx Server So you've got your Nginx server running smoothly wit...