To build a Linux-based router and firewall, first choose the appropriate Linux distribution, and it is recommended to use Debian as a starter. 1. Select a lightweight, stable and well-supported system, such as Debian, Alpine Linux or OpenWrt; 2. Configure at least two network interfaces: WAN (connected to the Internet) and LAN (connected to the intranet), and set IP parameters in /etc/network/interfaces; 3. Enable IP forwarding, and enable the system to support routing functions by modifying /etc/sysctl.conf and executing net.ipv4.ip_forward=1; 4. Configure NAT using iptables or nftables to realize that intranet devices share public IP. Key commands include MASQUERADE and FORWARD chain rules, and save configuration; 5. Establish a basic firewall policy to allow loopback, established connections and intranet access, prevent external direct access to the internal network, and open port forwarding if necessary; 6. Optionally deploy DHCP and DNS services, use dnsmasq to automatically allocate IP and resolve domain names to the LAN; 7. Strengthen the router's own security, disable the SSH login of root, enable key authentication, change the default port, install fail2ban brute-proof cracking and keep the system updated; 8. Regularly monitor logs and traffic, use syslog, iftop and other tools to troubleshoot problems, and back up configuration files. By implementing these steps step by step, you can create a secure, controllable, and highly customizable network gateway suitable for learning, experimental or production environments and have the ability to extend QoS, VLAN, or VPN capabilities.
Building a Linux-based router and firewall is a powerful way to gain full control over your network's traffic, security, and performance—without relying on consumer-grade hardware. With Linux, you can turn an old PC or a compact device like a Raspberry Pi or Intel NUC into a robust, customized gateway that routes traffic between networks and enforces security policies using built-in tools like iptables
or nftables
.

Here's how to set it up effectively.
1. Choose the Right Linux Distribution
Not all Linux distros are built for routing. You want something lightweight, stable, and with strong networking support.

- Debian or Ubuntu Server : Great balance of stability and package availability. Ideal if you're learning or want broad community support.
- Alpine Linux : Extremely lightweight, fast, and secure—perfect for older hardware or embedded systems.
- CentOS Stream or Rocky Linux : Enterprise-grade stability, good for production environments.
- OpenWrt (for small devices) : Specifically designed for routers, runs well on low-resource hardware.
For most DIY setups, Debian is a solid starting point.
2. Set Up Network Interfaces
A basic router needs at least two network interfaces:

- WAN (External) : Connects to the internet (eg, your modem).
- LAN (Internal) : Connects to your local network (eg, switch or Wi-Fi AP).
Example Setup:
eth0 → WAN (DHCP or static from ISP) eth1 → LAN (static IP, eg, 192.168.1.1)
Configure /etc/network/interfaces
(Debian/Ubuntu):
auto eth0 iface eth0 inet dhcp auto eth1 iface eth1 inet static address 192.168.1.1 netmask 255.255.255.0 network 192.168.1.0
Then restart networking:
sudo systemctl restart networking
3. Enable IP Forwarding
Linux doesn't forward packets between interfaces by default. Enable it via sysctl:
Edit /etc/sysctl.conf
and uncomment or add:
net.ipv4.ip_forward=1
Apply immediately:
sudo sysctl -p
Now the system can route packets from LAN to WAN and back.
4. Configure NAT with iptables or nftables
Use Network Address Translation (NAT) so your internal devices can share the single public IP.
With iptables
:
# Replace eth0 with your WAN interface sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE sudo iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT sudo iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT
Save rules (Debian/Ubuntu):
sudo iptables-save > /etc/iptables/rules.v4
On reboot, rules will be restored if you have iptables-persistent
installed.
Note :
nftables
is the modern replacement. If your system uses it, translate these rules accordingly.
5. Set Up a Basic Firewall
Your Linux router should block unwanted traffic while allowing legitimate use.
Common Rules:
- Allow loopback
- Allow established connections
- Allow LAN-to-WAN
- Block WAN-to-LAN unless explicitly allowed (eg, port forwarding)
Example iptables
firewall script:
#!/bin/bash iptables -F iptables -t nat -F # Allow loopback iptables -A INPUT -i lo -j ACCEPT iptables -A OUTPUT -o lo -j ACCEPT # Allow established traffic iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT # Allow LAN to router (SSH, DNS, DHCP if hosted) iptables -A INPUT -i eth1 -j ACCEPT # Block WAN to router unless needed iptables -A INPUT -i eth0 -j DROP # NAT and forwarding as before iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE iptables -A FORWARD -i eth1 -o eth0 -j ACCEPT iptables -A FORWARD -i eth0 -o eth1 -m state --state RELATED,ESTABLISHED -j ACCEPT # Enable forwarding echo 1 > /proc/sys/net/ipv4/ip_forward
Make it executable and run at boot.
6. Optional: Add DHCP and DNS Services
To make your router more functional, run DHCP and DNS services for your LAN.
Use ISC DHCP Server or dnsmasq (lighter, combines DHCP DNS).
Install dnsmasq:
sudo apt install dnsmasq
Edit /etc/dnsmasq.conf
:
interface=eth1 dhcp-range=192.168.1.100,192.168.1.200,12h server=8.8.8.8.8 domain-needed bogus-priv
Restart:
sudo systemctl restart dnsmasq
Now devices on your LAN can get IPs automatically.
7. Secure the Router Itself
Your router is a high-value target. Harden it:
- Disable root login over SSH
- Use SSH key authentication
- Change default SSH port (optional)
- Install fail2ban to block brute-force attempts
- Keep the system updated
sudo apt install fail2ban
8. Monitor and Maintain
- Check logs:
tail -f /var/log/syslog
orjournalctl -f
- Monitor traffic:
iftop
,nethogs
- Test connectivity from client devices
- Backup your config regularly
Building a Linux-based router gives you transparency, flexibility, and control. Whether you're learning networking, setting up a lab, or replacing a flaky consumer router, this approach scales from simple to advanced use cases—like QoS, VLANs, or even a VPN gateway.
It's not plug-and-play, but the payoff in learning and capability is huge.
Basically, start small, test each step, and grow from there.
The above is the detailed content of Building a Linux-based Router and Firewall. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

LXD is described as the next-generation container and virtual machine manager that offers an immersive for Linux systems running inside containers or as virtual machines. It provides images for an inordinate number of Linux distributions with support

Clear Linux OS is the ideal operating system for people – ahem system admins – who want to have a minimal, secure, and reliable Linux distribution. It is optimized for the Intel architecture, which means that running Clear Linux OS on AMD sys

The key steps for creating a self-signed SSL certificate are as follows: 1. Generate the private key, use the command opensslgenrsa-outselfsigned.key2048 to generate a 2048-bit RSA private key file, optional parameter -aes256 to achieve password protection; 2. Create a certificate request (CSR), run opensslreq-new-keyselfsigned.key-outselfsigned.csr and fill in the relevant information, especially the "CommonName" field; 3. Generate the certificate by self-signed, and use opensslx509-req-days365-inselfsigned.csr-signk

Decompress the .zip file on Windows, you can right-click to select "Extract All", while the .tar.gz file needs to use tools such as 7-Zip or WinRAR; on macOS and Linux, the .zip file can be double-clicked or unzip commanded, and the .tar.gz file can be decompressed by tar command or double-clicked directly. The specific steps are: 1. Windows processing.zip file: right-click → "Extract All"; 2. Windows processing.tar.gz file: Install third-party tools → right-click to decompress; 3. macOS/Linux processing.zip file: double-click or run unzipfilename.zip; 4. macOS/Linux processing.tar

Firefox browser is the default browser for most modern Linux distributions such as Ubuntu, Mint, and Fedora. Initially, its performance might be impressive, however, with the passage of time, you might notice that your browser is not as fast and resp

When encountering DNS problems, first check the /etc/resolv.conf file to see if the correct nameserver is configured; secondly, you can manually add public DNS such as 8.8.8.8 for testing; then use nslookup and dig commands to verify whether DNS resolution is normal. If these tools are not installed, you can first install the dnsutils or bind-utils package; then check the systemd-resolved service status and configuration file /etc/systemd/resolved.conf, and set DNS and FallbackDNS as needed and restart the service; finally check the network interface status and firewall rules, confirm that port 53 is not

As a system administrator, you may find yourself (today or in the future) working in an environment where Windows and Linux coexist. It is no secret that some big companies prefer (or have to) run some of their production services in Windows boxes an

If you find that the server is running slowly or the memory usage is too high, you should check the cause before operating. First, you need to check the system resource usage, use top, htop, free-h, iostat, ss-antp and other commands to check CPU, memory, disk I/O and network connections; secondly, analyze specific process problems, and track the behavior of high-occupancy processes through tools such as ps, jstack, strace; then check logs and monitoring data, view OOM records, exception requests, slow queries and other clues; finally, targeted processing is carried out based on common reasons such as memory leaks, connection pool exhaustion, cache failure storms, and timing task conflicts, optimize code logic, set up a timeout retry mechanism, add current limit fuses, and regularly pressure measurement and evaluation resources.
