Adding URL IP Filtering in Nginx Configuration

Sept. 29, 2020

Adding URL Filtering in Nginx Configuration


I worked with a few Apache configurations back in the days when I was a junior system administrator for a small ISP. Throughout the years I sporadically work on projects that have some tie-in to web servers but always in the context of network engineering; which is a roundabout way to say I am a noob when it comes to web servers configuration. :)

This week I was exploring a few ways to filter URL based on IP addresses. One of my friends suggested adding the necessary configuration to Nginx, but being a network engineer, I thought adding a load balancer in front might be a better way to go. Long story short, I tried adding the configuration as listed on the documentation, https://docs.nginx.com/nginx/admin-guide/security-controls/controlling-access-proxied-tcp/:

nginx_ip_filtering.png

Since I am proxying the connection to backend gUnicorn then to Django, I thought the configuration would follow an order block like an 'include'; I just need to apply the IP filtering block, and once passed, it will get passed down to the proxy configuration:

location /<url> {

....allow <ip>;

....deny all;

}

location / {

....include proxy_params;

....proxy_pass http://unix:/run/gunicorn.sock;

}

However, that did not work. Thankfully, my friend Manoj knew better and showed me the right way to apply the configuration, which is either include the proxy config in the block or in the top-level config. I choose to include it in the block, as below:

location /<url> {

....allow <ip>;

....deny all;

....include proxy_params;

....proxy_pass http://unix:/run/gunicorn.sock;

}

location / {

....include proxy_params;

....proxy_pass http://unix:/run/gunicorn.sock;

}

Now that worked as expected! Since it was one of the things I did not see documented somewhere else when I checked, I figured I will note it here in case somebody else comes across the same issue.

Happy coding!

Eric

Return to blog