Issues with nginx allow deny rule

codehero44 asked:

I’ve searched around if anyone had the same issue as me but couldn’t find any related thread.

My plan is to deny everyone except one public IP address from visiting a subdomain. The root domain and subdomain are being hosted on different servers. In the near future I also plan to use this subdomain for php and sql (self hosted crm), right now I’m just using a static html file for testing. The subdomain is hosted using nginx 1.18 on Ubuntu Server 18.04.5 LTS. When visiting subdomain.domain.com I receive an 403 forbidden message. I also use Cloudflare for caching and cdn. From checking the logs (not in the code, just for testing purposes) it seems my IPv6 is being used, however I still receive the same error. Ofcourse I also restarted nginx when testing.

Here’s my default.conf

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name subdomain.domain.com;

    ssl_certificate /path/to/cert/public.pem;
    ssl_certificate_key /path/to/cert/private.pem;

    root /path/to/content;
    index index.html;

    allow public.ip.address;
    deny all;

    error_page 403 404 /;
}

What am I doing wrong?

My answer:


You haven’t configured the realip module to substitute the client’s IP address for CloudFlare’s IP address, so nginx is making allow/deny decisions based on CloudFlare’s IP address (and of course blocking it).

For example (pulled from my own Ansible nginx role):

$ cat roles/nginx/files/cloudflare 
# CloudFlare
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
set_real_ip_from 104.16.0.0/12;
set_real_ip_from 108.162.192.0/18;
set_real_ip_from 131.0.72.0/22;
set_real_ip_from 141.101.64.0/18;
set_real_ip_from 162.158.0.0/15;
set_real_ip_from 172.64.0.0/13;
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 188.114.96.0/20;
set_real_ip_from 190.93.240.0/20;
set_real_ip_from 197.234.240.0/22;
set_real_ip_from 198.41.128.0/17;
set_real_ip_from 2400:cb00::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2c0f:f248::/32;
set_real_ip_from 2a06:98c0::/29;
real_ip_header CF-Connecting-IP;

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.