Skip to content

Rate limit with ip doesn't work on Django 3/Nginx/Gunicorn #222

@bzimor

Description

@bzimor

Ratelimit based on user ip doesn't work completely on Django 3 app. Initially, it raised an error due to the absence of REMOTE_ADDR and this error was fixed with a new patch on main branch. Although, it can access to the user ip, it doesn't block any over limit on production. However, it works when I run the project using runserver 0.0.0.0:8000.
I deployed my django app with the following configurations:
nginx:

upstream my_app_server {
    server unix:/home/projects/my_app/src/gunicorn.sock fail_timeout=0;
}

server {
    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_redirect off;
...

gunicorn:

#!/bin/bash

NAME="my_app"
DJANGODIR=/home/projects/my_app/src
SOCKFILE=/home/projects/my_app/src/gunicorn.sock 
NUM_WORKERS=5 
DJANGO_SETTINGS_MODULE=my_app.settings 
DJANGO_WSGI_MODULE=my_app.wsgi
TIMEOUT=300

echo "Starting $NAME as `whoami`"

cd $DJANGODIR
source ../env/bin/activate
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH

exec ../env/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \\
--name $NAME \
--workers $NUM_WORKERS \
--timeout $TIMEOUT \
--bind=unix:$SOCKFILE \
--log-level=debug \
--log-file=-

I added this setting:

RATELIMIT_IP_META_KEY = 'HTTP_X_REAL_IP'

Also, I checked with PyMemcacheCache and LocMemCache, even I tried with custom middleware to change REMOTE_ADDR header, but no luck.
Any ideas?
Django version is 3.1.5.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions