将 WebSocket Secure 与 Nginx 和 Daphne 结合使用

Using WebSocket Secure with Nginx and Daphne

我一直在努力弄清楚这一切,但我终于有了一些与以下相关的东西:

nginx:

server {
    server_name example.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/example/example;
    }

    location / {
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        include proxy_params;
        proxy_pass http://unix:/tmp/daphne.sock;
    }

    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = www.example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


    listen 80;
    server_name example.com;
    return 404; # managed by Certbot
}

daphne.service:

[Unit]
Description=daphne daemon
After=network.target

[Service]
User=example
Group=www-data
WorkingDirectory=/home/example/example
StandardOutput=file:/var/example.log
StandardError=file:/var/example.log
ExecStart=/home/example/example/venv/bin/daphne \
          -u /tmp/daphne.sock \
          project.asgi:application

[Install]
WantedBy=multi-user.target

我只能使用 https。该页面确实加载了该页面。但是,如果我尝试建立一个 websocket 连接,它会因混合协议而失败。所以我将 'ws://' 更改为 'wss://',现在我得到 The URL 'wss://' is invalid. 我怎样才能让它工作?

这个问题很容易解决。在我的 JavaScript 我有

new WebSocket(
        window.location.protocol == 'https:' ? 'wss://' : 'ws://'
        + window.location.host
        + '/ws/'
);

我应该有的时候

new WebSocket(
        (window.location.protocol == 'https:' ? 'wss://' : 'ws://')
        + window.location.host
        + '/ws/'
);

注意括号。