Block IP Addresses with Middleware
A snippet showing how to block unwanted IPs using middleware.
# middleware.py
from django.http import HttpResponseForbidden
from django.conf import settings
class BlockIPMiddleware:
def __init__(self, get_response):
self.get_response = get_response
self.blocked_ips = set(getattr(settings, 'BLOCKED_IPS', []))
self.allowed_ips = set(getattr(settings, 'ALLOWED_IPS', []))
def __call__(self, request):
ip = request.META.get('REMOTE_ADDR')
if ip in self.blocked_ips and ip not in self.allowed_ips:
return HttpResponseForbidden("Access denied.")
return self.get_response(request)
# settings.py
MIDDLEWARE = [
# ...
'your_app.middleware.BlockIPMiddleware',
]
# Simple deny/allow lists (strings must match client IP)
BLOCKED_IPS = ['203.0.113.10', '198.51.100.23']
ALLOWED_IPS = ['203.0.113.42'] # optional "allow override"
# middleware.py (CIDR support - optional)
import ipaddress
from django.http import HttpResponseForbidden
from django.conf import settings
class BlockCIDRMiddleware:
def __init__(self, get_response):
self.get_response = get_response
self.blocked_networks = [ipaddress.ip_network(n) for n in getattr(settings, 'BLOCKED_NETWORKS', [])]
def __call__(self, request):
ip = ipaddress.ip_address(request.META.get('REMOTE_ADDR'))
if any(ip in net for net in self.blocked_networks):
return HttpResponseForbidden("Access denied.")
return self.get_response(request)
Explanation:
-
Middleware checks a request's
REMOTE_ADDRbefore the view runs and blocks listed IPs with a 403. -
Configure
BLOCKED_IPS(and optionalALLOWED_IPS) insettings.pyto manage access centrally. -
For ranges, the optional CIDR version uses Python's
ipaddressto block entire networks. -
Behind proxies/load balancers, prefer trusted headers like
X-Forwarded-For; sanitize and trust only from known proxies.
- Category Middleware
- Total Views 372
- Last Modified 27 March, 2026
- Tags #middleware #security #ip #block
Previous snippet
Logging Requests in Middleware
Next snippet