nginx 根路径同时代理 http ws sse 三种请求

HTTP(HyperText Transfer Protocol):超文本传输协议,是用于在客户端(通常是web浏览器)和服务器之间传输数据的协议。HTTP是Web的基础,用于请求和传输网页、图像、视频等资源。它采用请求-响应模型,支持多种方法(如GET、POST等),并可通过HTTP/1.1和HTTP/2等版本进行优化,以提高性能和用户体验。

WebSocket:WebSocket是一种在单个TCP连接上进行全双工通信的协议。它允许客户端和服务器之间实现实时双向数据传输。WebSocket通过握手过程建立连接,并在一次握手后保持该连接,从而减少了HTTP请求的开销,适合实时应用如在线聊天、股票实时更新等。

SSE(Server-Sent Events):服务器推送事件是一种通过HTTP协议向浏览器推送实时事件的技术。与WebSocket不同,SSE是单向的,数据从服务器流向客户端。它使用 text/event-stream MIME类型,适用于需要实时更新但不需要客户端响应的场合,如实时新闻推送、股票价格更新等。SSE易于使用并支持自动重连。

利用 map 实现

map 定义的就是一个字典(k,v),通过不同key,映射不同value值。

nginx 复制代码
http {
    map $http_content_type $connection_header {
        default "upgrade";
        "text/event-stream" "keep-alive";
    }

    upstream http_backend {
        server 127.0.0.1:80;
    }

    server {
        listen 9123;
        # server_name your_domain_name;

        location / {
            proxy_pass http://http_backend;
            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_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_header;
            proxy_cache off;
        }
    }
}

使用 if 和变量实现

if 表达式里面不能直接包含指令 proxy_set_header Connection keep-alive,会报错,但是可以包含变量间接实现。

nginx 复制代码
upstream http_backend {
    server 127.0.0.1:80;
}

server {
    listen 9123;
    # server_name your_domain_name;

    location / {
        set $connection_header "upgrade";

        if ($http_content_type ~* "text/event-stream") {
            set $connection_header "keep-alive";
        }

        proxy_pass http://http_backend;
        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_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_header;
        proxy_cache off;
    }
}
相关推荐
xie_pin_an3 小时前
网络原理与编程实战:从 TCP/IP 到 HTTP/HTTPS
网络·tcp/ip·http
teeeeeeemo3 小时前
如何做HTTP优化
前端·网络·笔记·网络协议·http
weisian1513 小时前
HTTP协议-4-浏览器是怎么抉择HTTP版本的?
网络·网络协议·http
水冗水孚6 小时前
图文并茂讲解nginx中http升级https(部署SSL证书)知识点总结
nginx·http·https
athink_cn20 小时前
HTTP/2新型漏洞“MadeYouReset“曝光:可发动大规模DoS攻击
网络·网络协议·安全·http·网络安全
HYI1 天前
小公司前端多分支测试太痛苦?我自己写了个轻量 CLI
nginx·vite
timeweaver1 天前
深度解析 Nginx 前端 location 配置与优先级:你真的用对了吗?
前端·nginx·前端工程化
Moment1 天前
nginx 如何配置防止慢速攻击 🤔🤔🤔
前端·后端·nginx
网络研究院1 天前
新的“MadeYouReset”方法利用 HTTP/2 进行隐秘的 DoS 攻击
网络·网络协议·安全·http·攻击·漏洞
玩转以太网2 天前
基于W55MH32Q-EVB 实现 HTTP 服务器配置 OLED 滚动显示信息
服务器·网络协议·http