Nginx configuration for allow ip is not working deny all is working fine

11,395

at last i find out the cause of the issue why the allow ip: deny all;

not working .its becasue its loading with a proxy ip while connecting to the site. so we want to enalbe the proxy ip also if we want to allow for a specific public ip. here are the configuration .

upstream backend_solr {
    ip_hash;
    server ip_address:port; 
} 
server {
    listen 80;
    server_name www.example.com;

    index /example/admin.html;

     charset utf-8;
     access_log /var/log/nginx/example_access.log main;

     location / {
         # **
         set $allow false;
         if ($http_x_forwarded_for ~ " 12\.22\.22\.22?$")-public ip {
             set $allow true;
         }
         set $allow false;
         if ($http_x_forwarded_for ~ " ?11\.123\.123\.123?$")- proxy ip {
             set $allow true;
         }
         if ($allow = false) {
             return 403 ;
         }
         # **
         proxy_pass  http://backend_solr-01/;
         proxy_set_header Host $host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    location ~ /favicon\.ico {
        root html;
    }

    location ~ /\. {
        deny all;
    }
}
Share:
11,395
fatha
Author by

fatha

Updated on June 29, 2022

Comments

  • fatha
    fatha almost 2 years

    i create a new conf file to block all public ip to access and give only one public ip address(office public IP) to access. but when i try to access its shows the "403 Forbidden nginx"

        upstream backend_solr {
             ip_hash;
             server ip_address:port; 
    } 
    server {
             listen 80;
             server_name www.example.com;
    
             index /example/admin.html;
    
             charset utf-8;
             access_log /var/log/nginx/example_access.log main;
    
             location / {
    
                allow **office_public_ip**;
                deny all;
                proxy_pass  http://backend_solr-01/;
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
             }
    
            location ~ /favicon\.ico {
                root html;
            }
    
            location ~ /\. {
                deny all;
            }}
    

    but in the logs it shows accessing to the public ip but forbidden

    IP_Address - - [31/Jul/2017:12:43:05 +0800] "Get /example/admin.html HTTP/1.0" www.example.com "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36" "my_office _IP" "-" "-" "-" 403 564 0.000 - - -