Score:1

How can I restrict access from external IP's for a ngnix location

cn flag

I want to restrict access to an ngnix location from external IP's. I add the following configuration to the ngnix config file, but I am not sure if it is the right way to do so. Is there any better alternatives for restricting the external IP's to access a location?

map $proxy_add_x_forwarded_for $remote_ip {
    default     $proxy_add_x_forwarded_for;
    ""          $http_x_real_ip;
}
map $remote_ip $isinternal {
    ~^127\.                                             1;
    ~^10\.                                              1;
    ~(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.) 1;
    ~^192\.168\.                                        1;
    default                                             0;
}

...

location /app/sniper {
    if ($isinternal != 1) { return 403; }
    ...
}

Thanks in advance...

Score:2
us flag

You should use nginx geo module for IP address maps. Your configuration would be like this with it:

geo $internal {
    default        0;
    127.0.0.0/8    1;
    10.0.0.0/8     1;
    172.16.0.0/20  1;
    192.168.0.0/24 1;
}

location /app/sniper {
    if ($internal != 1) {
        return 403;
    }
}
Kemal Kaplan avatar
cn flag
Tero thanks for the response, do you have any comments for getting the real IP? Is there a better way to get the real IP where I search http_x_real_ip and _x_forwarded_for?
us flag
If you are behind a proxy, I would use https://nginx.org/en/docs/http/ngx_http_realip_module.html to get the IP address.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.