Protect Django Admin by IP in NGINX / Gunicorn behind an AWS Load Balancer

Apr 12, 2017
NGINX
Protect Django Admin Subdirectory

Here’s how you can easily protect Django admin by blocking unwanted IP addresses using NGINX and Gunicorn when behind an AWS Load Balancer.

Django Admin

The Django Admin app is great. This included tool allows you easily set up a password-protected section of your website, allowing administrators to manage site data with a simple and intuitive interface. Now, the password protection may be enough security for what you need, especially when delivered through HTTPS.  But, it’s also nice to be able to prevent global access to that section completely, denying hackers a way to use techniques like brute-force attacks to gain access to your data.

Blocking by IP is easily done in both Apache and NGINX with some simple allow/deny rules.  But when your Django site is running on an EC2 instance behind an AWS Elastic Load Balancer (ELB) at Amazon, you have to handle blocking a bit differently. The IP that is sent to your server is actually the ELB’s IP, not the remote client’s address. The load balancer actually stores the client IP in the X-Forwarded-For request header, which you can pick off and use in the NGINX site configuration.

NGINX Configuration

Here’s a configuration file snippet for NGINX showing how to protect Django admin by blocking the /admin/ subdirectory from any unauthorized IP addresses when proxying to Gunicorn to serve up your Django site:

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *