Feb 22, 2025
Using nftables, configure the site to only allow cloudflare IPs access
In this article, we will guide you through the process of configuring nftables to allow only Cloudflare IPs to access your site over HTTP and HTTPS while blocking all other IPs.
1. Get Cloudflare IP Addresses
As mentioned earlier, you need to obtain Cloudflare’s IPv4 and IPv6 IP ranges. You can find this information on the following pages:
2. Edit nftables Configuration
Assuming you want to allow all traffic but deny only HTTP and HTTPS traffic from non-Cloudflare IPs, you can configure nftables
as follows:
1 | # nftables configuration file |
Configuration Explanation:
policy accept
: The default action is to accept all traffic.iif lo accept
: Allows traffic from the local loopback interface (localhost), ensuring local services aren’t blocked.tcp dport {22} accept
: Allows SSH traffic (if you use a different port, adjust accordingly).ip saddr { ... } tcp dport {80, 443} accept
: Allows Cloudflare’s IPs to access HTTP (80) and HTTPS (443) ports.ip daddr != { ... } tcp dport {80, 443} drop
: Denies all non-Cloudflare IPs from accessing HTTP and HTTPS ports.
This configuration ensures that only Cloudflare’s IP addresses can access your HTTP and HTTPS services, while other IP addresses are denied access to these two ports. However, other traffic (like SSH) will remain unaffected.
3. Load nftables Configuration
After saving the configuration file, load the new rules with the following command:
1 | sudo nft -f /etc/nftables.conf |
4. Verify the Rules
To verify if the rules have been applied correctly, run the following command:
1 | sudo nft list ruleset |
5. Persist nftables Configuration
To ensure the configuration persists after a reboot, enable the nftables
service:
1 | sudo systemctl enable nftables |
Summary:
With this setup, only HTTP (80) and HTTPS (443) traffic will be denied for non-Cloudflare IP addresses, while other types of traffic (like SSH) will be allowed. This way, only Cloudflare’s IPs will be able to access your website’s HTTP and HTTPS services, and all other IPs will be denied access to these two ports.