首页 > 解决方案 > 可以仅使用 Nginx 和 Daphne 为 Django Channels 应用程序提供服务吗?

问题描述

我假设我可以只使用(ASGI)运行一个Django Channels应用程序,并作为我的 Django 应用程序的代理开始。DaphneNginx

该应用程序将运行Daphne127.0.0.1:8001

但是,我遇到了一个403 Forbidden错误。

2019/03/06 17:45:40 [error] *1 directory index of "/home/user1/app/src/app/" is forbidden

当我发布有关此内容时,另一位用户提到

在您的 nginx 配置中没有将 http 请求传递给 django 应用程序的指令

并建议查看fastcgi_passor uwsgi_passor Gunicorn

显然 Django Channels 正在运行ASGI,我现在正在通过它传递所有请求(而不是uWSGI然后ASGI取决于请求。)

我可以只用Nginxand服务我的 Django 应用程序Daphne吗?Django Channels 文档似乎这样认为,因为他们没有提到需要 Gunicorn 或类似的东西。

我的 nginx 配置

upstream socket {
    ip_hash;
    server 127.0.0.1:8001 fail_timeout=0;
}

server {

    listen 80;
    #listen [::]:80 ipv6only=on;

    server_name your.server.com;
    access_log /etc/nginx/access.log;

    root /var/www/html/someroot;

    location / {
            #autoindex on;

            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            # try_files $uri =404;

            #proxy_set_header X-Real-IP $remote_addr;
            #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            #proxy_set_header Host $http_host;
            #proxy_set_header X-NginX-Proxy true;
            #proxy_pass http://socket;
            #proxy_redirect off;
            #proxy_http_version 1.1;
            #proxy_set_header Upgrade $http_upgrade;
            #proxy_set_header Connection "upgrade";

            #proxy_redirect off;
            #proxy_set_header   X-Forwarded-Proto $scheme;
            #proxy_cache one;
            #proxy_cache_key sfs$request_uri$scheme;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/some/fullchain.pem;
    # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/some/privkey.pem; 
    # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    }
}

标签: djangonginxdjango-channelsdaphne

解决方案


是的,这是可能的。试试这个配置:

upstream socket {
    ip_hash;
    server $DAPHNE_IP_ADDRESS$ fail_timeout=0;
}

server {
    ...

    location / {
        proxy_pass http://socket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    ...
}

其中 $DAPHNE_IP_ADDRESS$ - 你的 daphne IP 和端口,没有 schema( 127.0.0.1:8001)。


推荐阅读