How to configure iptables to secure Apache server on Ubuntu

Where necessary, you may need to have access to a VPS server so you can follow how to implement the steps in this article.  You can get a cheaper VPS Server from Contabo with 4vCPU cores, 8GM RAM, and 32TB Bandwidth for less than $5.50 per month. Get this deal here now

Table of Contents

Cloud VPS S

$5.50 Monthly
  • 4 vCPU Cores | 8GB RAM


$15.50 Monthly
  • 6 vCPU Cores | 16GB RAM


$17.50 Monthly
  • 8 vCPU Cores | 24GB RAM

iptables can allow you to define the firewall rules for filtering incoming and outgoing traffic based on a variety of criteria, such as the source or destination IP address, the protocol (TCP, UDP, etc.), or the source or destination ports. It is used to set up, maintain, and inspect the tables of IP packet filter rules in the Linux kernel. Several different tables may be defined, each containing several built-in chains and may also contain user-defined chains.

In this guide, we would like to understand how to secure Apache server using iptables, allowing appropriate traffic and dropping or blocking undesirable traffic.

Install iptables

if you don’t have iptables installed on your Linux server, then you need to run the following command to install it;

sudo apt install iptables

To check if iptables is available on your system, you can run the following command:

iptables --version

If iptables is installed, you will see information about the installed version:

root@ubuntu-c-4-8gib-nyc3-01:~# iptables --version
iptables v1.8.7 (nf_tables)

If it’s not installed, you might get a message indicating that the command is not found.

Set Default Policies

The default iptables policies are designed to filter incoming traffic and only allow through the connections that are explicitly permitted. This can be achieved by enforcing the following iptables rules:

sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

These commands set the default policy to drop incoming and forwarded packets and accept outgoing packets.

Alternatively, you can flush the existing rules, which will make sure your iptables are configured to default so you can configure custom rules based on your needs;

sudo iptables -Fsudo iptables -P INPUT DROP
sudo iptables -P OUTPUT DROPsudo iptables -P FORWARD DROP

Allow wanted incoming connections

Wanted incoming traffic is the connection that’s explicitly allowed to make connection requests to the server. To secure mission-critical webservers, every traffic coming in should be clearly defined, and unwanted traffic should be locked out.

Allow incoming HTTP and HTTPS traffic

HTTP (Hypertext Transfer Protocol) is a protocol that is used for transferring data over the internet. It is the foundation of the World Wide Web and is used for transmitting data between web browsers and web servers. When a user enters a URL (Uniform Resource Locator) into their web browser, the browser sends an HTTP request to the webserver to retrieve the webpage associated with that URL. The web server then sends back an HTTP response, which includes the requested webpage as well as other information such as HTTP headers.

The Apache web server requires port 80 to be opened to allow incoming HTTP traffic. We can achieve this by implementing the following iptables rule:

sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT

On the other hand, HTTPS (HTTP Secure) is an extension of HTTP that adds an additional layer of security. It uses SSL (Secure Sockets Layer) or TLS (Transport Layer Security) to encrypt the data being transmitted between the web browser and the web server. This encryption helps to protect against eavesdropping and tampering of the data in transit, which can happen on public networks. When a user enters a URL that starts with “https” instead of “HTTP”, the browser sends an HTTPS request to the webserver to retrieve the webpage associated with that URL.

The web server then sends back an HTTPS response, which includes the requested webpage as well as other information such as HTTP headers, and the communication between the browser and the server is encrypted.

HTTPS is commonly used on e-commerce websites, online banking, and other websites where security and privacy are important. Websites that use HTTPS may also display a padlock icon in the browser and the URL bar may turn green to indicate that the connection is secure.

Now, you will have to configure iptables to allow traffic to and from these two protocols by opening their ports or setting up custom ports for them. Port 80 is the default port for HTTP and port 443 is the default for HTTPS traffic.

The HTTPS traffic goes through port 443 by default. This means that the Apache web server will require this port to be opened. This can be done using the following iptables rule:

sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

Allow incoming SSH traffic

Allowing incoming traffic on port 22 for SSH is particularly useful for servers, where it enables remote management and administration.

sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

You also need to understand that opening the SSH port can increase the risk of unauthorized access to your server so it is important to secure your SSH setup with strong authentication with mechanisms like key-based authentication

Only open FTP port 21 when you need it

It’s a good security practice to only open ports that are necessary for the operation of your services, and close them when they are not needed. This principle is known as the “principle of least privilege.” By restricting open ports to only those required for specific services, you reduce the attack surface and minimize potential security risks.

In the context of FTP (File Transfer Protocol), port 21 is the default command port, used for sending commands and receiving responses. However, FTP also requires additional ports for data transfer. In active FTP mode, the server opens a random port (usually in the range 1024-65535) for data transfer, and the client connects to this port. In passive FTP mode, the client opens a random port for data transfer, and the server connects to this port.

If you’re using FTP and want to follow the principle of least privilege:

Open Only Port 21

Allow incoming traffic on port 21 for FTP command connections:

sudo iptables -A INPUT -p tcp --dport 21 -j ACCEPT

Allow Additional Ports for Passive FTP

If you’re using passive FTP, you’ll need to allow incoming traffic on the range of ports used for passive data connections. You can specify a range of ports or open a wide range (e.g., 1024-65535) if the FTP server uses dynamic port allocation:

sudo iptables -A INPUT -p tcp --sport 1024:65535 -m state --state ESTABLISHED -j ACCEPT

Close the Ports When Not Needed

If you’re not actively using FTP, consider closing the ports:

sudo iptables -A INPUT -p tcp --dport 21 -j DROP
sudo iptables -A INPUT -p tcp --sport 1024:65535 -m state --state ESTABLISHED -j DROP

Block Outgoing Connections on Specific Ports

Outgoing connections refer to network connections initiated by your device (client) to external servers or services. These connections are established when your device makes requests or communicates with other devices on the internet or within a local network. Outgoing connections are essential for various applications and services to function properly.

If your Apache server does not need to make outgoing connections on specific ports, you can block them.

sudo iptables -A OUTPUT -p tcp --dport <port_number> -j DROP

Replace <port_number> with the actual port number you want to block for outgoing connections.

When do you need to allow outgoing traffic?

A web server may need outgoing connections open for various reasons, depending on its specific functionalities and requirements. Here are common scenarios where outgoing connections from a web server are necessary:

  • Fetching Updates

The server may need to fetch updates for the operating system, web server software (e.g., Apache, Nginx), and other installed packages. Outgoing connections are necessary to connect to package repositories and download updates.

  • Content Delivery

If your web server serves dynamic content, it may need to connect to external APIs, databases, or content delivery networks (CDNs) to fetch and deliver content to clients.

  • Third-Party Integrations

Web applications often integrate with third-party services or APIs for various purposes, such as payment processing, user authentication, and social media interactions. Outgoing connections are required to communicate with these external services.

Applications interacting with cloud services, such as making API requests to services like AWS, Google Cloud, or Azure, establish outgoing connections to the respective service endpoints.

  • Logging and Monitoring

Outgoing connections may be necessary for logging purposes. Web servers may need to send logs to external logging servers or services. Monitoring solutions that provide insights into server performance may also require outgoing connections.

  • Email Services

If your web application sends emails, the server may need to connect to an external SMTP server to deliver email messages.

  • DNS Resolution

Web servers often need to resolve domain names to IP addresses. Outgoing connections to DNS servers (UDP port 53) are essential for DNS resolution.

  • Security Updates and Anti-Virus

Outgoing connections may be required for security-related tasks, such as checking for security updates or connecting to anti-virus services for scanning purposes.

  • Authentication and Authorization

Outgoing connections may be needed for user authentication and authorization purposes. For example, a web server might connect to an authentication service to verify user credentials.

  • License Verification:

Some software used by web servers may require outgoing connections to verify licensing or check for software updates.

Block Specific IP Addresses or Ranges

Blocking specific IP addresses is often employed as a countermeasure against repeated login attempts, distributed denial-of-service (DDoS) attacks, or any form of malicious traffic originating from specific sources. For example, if there is evidence of a particular IP address attempting to exploit vulnerabilities or engage in suspicious behavior, blocking that IP address can prevent further unauthorized access and protect the server’s integrity.

Block Incoming Traffic from Specific IP Addresses

Using iptables, you can block incoming traffic from specific IP addresses, ranges, and CIDR blocks by creating rules in the INPUT chain.

It’s important to understand that you can only IP addresses to access your web application if you think that they pose a serious security danger.

Now, here are some examples of blocking incoming traffic from a specific IP address, a range of IP addresses, and a CIDR block:

  • Block a Specific IP Address

To block incoming traffic from a specific IP address, use the following command:

sudo iptables -A INPUT -s <IP_ADDRESS> -j DROP

Replace <IP_ADDRESS> with the actual IP address you want to block.

  • Block a Range of IP Addresses

To block incoming traffic from a range of IP addresses, you can use the iprange module:

sudo iptables -A INPUT -m iprange --src-range 2xx.3x.1xx.125-2xx.3x.1xx.225 -j DROP

Replace 2xx.3x.1xx.125 and 2xx.3x.1xx.225 with the start and end IP addresses of the range you want to block.

  • Block a CIDR Block

To block incoming traffic from a CIDR block, use the following command:

sudo iptables -A INPUT -s <CIDR_BLOCK> -j DROP

Replace <CIDR_BLOCK> with the CIDR notation for the block you want to block (e.g.,

sudo iptables -A INPUT -s -j DROP

RECOMMENDED READING: How to block countries using iptables firewall on Linux

Save the iptables rules

Saving the iptables firewall rules requires you to first install the iptables-persistent package by running the following command;

sudo apt-get install iptables-persistent

Once you’ve finished installing the iptables-persistent package on your system, you can save the implemented firewall rules by running the following command:

sudo sh -c "iptables-save > /etc/iptables/rules.v4"

More related articles to explore

Hire us to handle what you want

Hire us through our Fiverr Profile and leave all the complicated & technical stuff to us. Here are some of the things we can do for you:

  • Website migration, troubleshooting, and maintenance.
  • Server & application deployment, scaling, troubleshooting, and maintenance
  • Deployment of Kubernetes, Docker, Cloudron, Ant Media, Apache, Nginx,  OpenVPN, cPanel, WHMCS, WordPress, and more
  • Everything you need on AWS, IBM Cloud, GCP, Azure, Oracle Cloud, Alibaba Cloud, Linode, Contabo, DigitalOcean, Ionos, Vultr, GoDaddy, HostGator, Namecheap, DreamHost, and more.

We will design, configure, deploy, or troubleshoot anything you want. Starting from $10, we will get your job done in the shortest time possible. Your payment is safe with Fiverr as we will only be paid once your project is completed.