PortGate

Resources · Security guides · Security guide

Lock the origin to Cloudflare, after the tunnel or proxy works

A Cloudflare-proxied site whose server still answers on its public IP can be attacked directly. Use a Cloudflare Tunnel or allow only Cloudflare IP ranges, in an order that does not take the site down.

Check command

curl -sk -o /dev/null -w '%{http_code}\n' --resolve example.com:443:YOUR.ORIGIN.IP https://example.com/

Copied.

Cloudflare's WAF, rate limits and DDoS protection only apply to traffic that goes through Cloudflare. If the server's own IP still answers on ports 80 and 443, an attacker who finds that IP (old DNS records, mail headers, certificate logs) skips all of it.

Check whether the origin answers directly

From a machine outside your network:

curl -sk -o /dev/null -w '%{http_code}\n' --resolve example.com:443:YOUR.ORIGIN.IP https://example.com/

200 or a redirect means the origin is reachable without Cloudflare. A timeout means it is locked.

Option 1: Cloudflare Tunnel (no open web ports)

cloudflared makes an outbound connection to Cloudflare, so the server needs no inbound 80 or 443 at all.

  1. Install cloudflared and create the tunnel from the Cloudflare dashboard (Zero Trust, Networks, Tunnels). It gives you an install command with a token.
  2. Add a public hostname that points to http://127.0.0.1:80 (or wherever nginx listens).
  3. Confirm the site loads through the tunnel.
  4. Only then remove the web ports from the firewall:
sudo ufw delete allow 80/tcp
sudo ufw delete allow 443/tcp

Bind nginx to 127.0.0.1 so nothing else can reach it. Leave SSH alone: the tunnel does not carry your SSH session unless you set that up separately.

Option 2: allow only Cloudflare's IP ranges

If you keep the DNS proxy (orange cloud) without a tunnel, allow 443 only from Cloudflare's published ranges:

for net in $(curl -fsS https://www.cloudflare.com/ips-v4) $(curl -fsS https://www.cloudflare.com/ips-v6); do
  sudo ufw allow proto tcp from "$net" to any port 443
done
sudo ufw delete allow 443/tcp

Add the new rules first, check the site, then delete the open rule. Cloudflare occasionally changes its ranges, so rerun this from a scheduled job. If the site runs in Docker with a published port, UFW does not filter it: filter in the DOCKER-USER chain instead.

Restore real visitor IPs

Behind Cloudflare, nginx sees Cloudflare's address. Set set_real_ip_from for each Cloudflare range and real_ip_header CF-Connecting-IP;, so logs and rate limits use the visitor's IP. Only trust that header from Cloudflare's ranges, or anyone can forge it.

Change the origin IP if it was public for a long time

An IP that has been in DNS for years is in historical DNS databases. Moving to a new server IP after locking down is the only way to make the old one useless.