一、导读
nginx 是一个反向代理的轻量服务器,能对http请求进行转发,但是最新学习websocket发现,普通的nginx转发http请求时候无法转发websocket请求,今天就来介绍一下nginx如何转发websocket请求;与普通的端口转发差不多,只需要修改或加多一两个配置信息。
二、修改nginx.conf配置文件
1. http模块配置如下
http {
include mime.types;
default_type application/octet-stream;
log_format '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /home/xxx/logs/access.log;
sendfile on;
keepalive_timeout 65;
# 添加 websocket 转发配置
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 8080;
server_name 127.0.0.1;
location /api {
# 添加 websocket 转发配置
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# 转发后台地址
proxy_pass http://127.0.0.1:8081/api;
}
}
}
2. 以上有2个地方配置好,即可实现websocket请求转发。