nginx配置websocket

非加密的WebSocket连接。

shell 复制代码
#ws`# 这是一个ws配置示例,表示使用非加密的WebSocket连接。  
server {  
    listen 8080;  
    server_name example.com;  
  
    location /websocket {  
        proxy_pass http://backend-server;  
        proxy_http_version 1.1;  
        proxy_set_header Upgrade $http_upgrade;  
        proxy_set_header Connection "upgrade";  
        proxy_set_header Host $host;  
        proxy_cache_bypass $http_upgrade;  
    }  
}

SSL/TLS加密的WebSocket连接

shell 复制代码
#wss`# 这是一个wss配置示例,表示使用SSL/TLS加密的WebSocket连接。  
server {  
    listen 443 ssl;  
    server_name example.com;  
  
    ssl_certificate /path/to/certificate.crt;  
    ssl_certificate_key /path/to/private_key.key;  
  
    location /websocket {  
        proxy_pass http://backend-server;  
        proxy_http_version 1.1;  
        # 这个指令设置了HTTP头Upgrade的值。
        # $http_upgrade是一个变量,它的值是HTTP请求头中的Upgrade字段的值。
        # WebSocket协议使用这个头字段来升级普通的HTTP连接为WebSocket连接。
        proxy_set_header Upgrade $http_upgrade;  
        # 这个指令设置了HTTP头Connection的值。
        # WebSocket协议使用这个头字段来指定连接的升级方向。
        # 在这里,它的值被设置为upgrade,表示这个连接应该被升级为WebSocket连接。
        proxy_set_header Connection "upgrade";  
        
        proxy_set_header Host $host;  
        proxy_cache_bypass $http_upgrade;  
    }  
}

简单说明

shell 复制代码
# 配置这两个参数,升级链接为 websocket 
# 如果有向下级代理转发,下级代理也需要配置此参数
        proxy_set_header Upgrade $http_upgrade;  
        proxy_set_header Connection "upgrade";  
        
# 而proxy_set_header Host $host;
# 和proxy_cache_bypass $http_upgrade;这两个指令不是必选的。

# proxy_set_header Host $host;:
# 这个指令设置了HTTP头Host的值,用于指定请求的主机名。
# 如果你在Nginx配置中已经设置了Host头字段的值,那么这个指令可以省略。

# proxy_cache_bypass $http_upgrade;:
# 这个指令指定了在某些情况下是否绕过缓存。
# 当HTTP请求头中的Upgrade字段的值与变量$http_upgrade的值匹配时,缓存将被绕过。
# 这确保了WebSocket连接不会被缓存,因为WebSocket连接是双向的,并且可能包含实时数据。
# 如果你不需要绕过缓存,这个指令也可以省略。        
相关推荐
yzx9910135 小时前
生活在数字世界:一份人人都能看懂的网络安全生存指南
运维·开发语言·网络·人工智能·自动化
橙*^O^*安6 小时前
Go 语言基础:变量与常量
运维·开发语言·后端·golang·kubernetes
阿拉斯加大闸蟹7 小时前
基于RDMA 通信的可负载均衡高性能服务架构
运维·架构·负载均衡
不是吧这都有重名8 小时前
为什么ubuntu大文件拷贝会先快后慢?
linux·运维·ubuntu
sunshine-sm8 小时前
CentOS Steam 9安装 Redis
linux·运维·服务器·redis·centos
棒棒的唐9 小时前
armbian平台ubuntu环境下telnet安装及启动,给pantherX2增加一个应急通道
linux·运维·armbian·telnetd
纳切威9 小时前
CentOS 7部署Zabbix5.0
linux·运维·centos·zabbix
sunshine-sm10 小时前
CentOS Steam 9安装 MySQL 8
linux·运维·服务器·数据库·mysql·centos·centos stream
bug攻城狮10 小时前
CentOS 7 快速检查软件包是否已安装的5种方法
linux·运维·centos
男孩李10 小时前
浅谈代理流程自动化 (APA)
运维·人工智能·自动化