使用 unix 套接字时,Django ALLOWED_HOSTS 应该是什么?

con*_*fin 5 django unix-socket gunicorn

我正在使用 unix 套接字而不是 gunicorn 的 TCP 端口来为我的 Django 应用程序提供服务。但是,当调试关闭时,我会收到 400 响应,除非我设置了ALLOWED_HOSTS = ['*']. 在这种情况下,有什么比 '*' 更安全的选项?

这是我的 Gunicorn 启动脚本(/opt/example.com/bin/gunicorn_start):

#!/bin/bash

NAME="myapp"                                      # Name of the application
DJANGODIR=/opt/example.com/myapp                  # Django project directory
SOCKFILE=/opt/example.com/run/gunicorn.sock       # we will communicate using this unix socket
USER= myuser                                      # the user to run as
GROUP=mygroup                                     # the group to run as
NUM_WORKERS=3                                     # how many worker processes should Gunicorn spawn
DJANGO_SETTINGS_MODULE=myapp.settings             # which settings file should Django use
DJANGO_WSGI_MODULE=myapp.wsgi                     # WSGI module name

echo "Starting $NAME as `whoami`"

# Activate the virtual environment
cd $DJANGODIR
source ../bin/activate
export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE
export PYTHONPATH=$DJANGODIR:$PYTHONPATH

# Create the run directory if it doesn't exist
RUNDIR=$(dirname $SOCKFILE)
test -d $RUNDIR || mkdir -p $RUNDIR

# Start your Django Unicorn
# Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon)
exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \
  --name $NAME \
  --workers $NUM_WORKERS \
  --user=$USER --group=$GROUP \
  --log-level=debug \
  --bind=unix:$SOCKFILE
Run Code Online (Sandbox Code Playgroud)

con*_*fin 2

结果我只需要添加服务器的主机名。我一直在使用 ['localhost', '127.0.0.1'],但由于我也添加了以下 nginx 配置,因此应用程序需要允许网站的 URL。

upstream blog_app_server {
  # fail_timeout=0 means we always retry an upstream even if it failed
  # to return a good HTTP response (in case the Unicorn master nukes a
  # single worker for timing out).

  server unix:/opt/example.com/run/gunicorn.sock fail_timeout=0;
}

server {
    listen       80;
    server_name  www.example.com example.com;
    server_tokens off;
    access_log /opt/example.com/logs/nginx-access.log;
    error_log /opt/example.com/logs/nginx-error.log;

    location /static/ {
        alias /opt/example.com/static/;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        if (!-f $request_filename) {
            proxy_pass http://blog_app_server;
            break;
        }
    }

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

}
Run Code Online (Sandbox Code Playgroud)

具体来说,我认为该行proxy_set_header Host $http_host;意味着我需要将站点名称添加到 ALLOWED_HOSTS 中。