修改 nginx 配置以正确反向代理 websockets

Modify nginx config to reverse proxy websockets properly

当前的 nginx 配置:

server {
    listen 443 ssl http2;
    server_name NAME www.NAME;
    charset utf-8;
    ssl on;
    ssl_certificate /etc/nginx/ssl/NAME-cert.pem;
    ssl_certificate_key /etc/nginx/ssl/NAME-key.pem;

    location /static/ {
        alias /home/ubuntu/NAME/static_collection/;
    }

    location /media/ {
    alias /home/ubuntu/NAME/media_collection/;
    }

    location / {
        proxy_pass http://localhost:8002;

    proxy_redirect off;
    proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

一切正常,除了 websockets。我想这是因为它不处理 http 升级 header...我看过文档,但我不知道如何在不破坏其他任何东西的情况下修改此配置。

试试这个。让我知道它是否有效。

server {
    listen 443 ssl http2;
    server_name NAME www.NAME;
    charset utf-8;
    ssl on;
    ssl_certificate /etc/nginx/ssl/NAME-cert.pem;
    ssl_certificate_key /etc/nginx/ssl/NAME-key.pem;

    location /static/ {
        alias /home/ubuntu/NAME/static_collection/;
    }

    location /media/ {
    alias /home/ubuntu/NAME/media_collection/;
    }

    location / {
        proxy_pass http://localhost:8002;

        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_http_version 1.1;
        proxy_read_timeout 86400;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
    }
}