原由
1.我有一个socket服务,用ip访问是成功的,但是老板说用这个不行,要用nginx请求转发,转发内网地址到某个域名
2.但是我改成了指定域名后失败,因为我没有配置nginx.conf
3.接下来一起学习下,怎么在nginx中配置socket转发
http的很简单,如下(---可跳过---)
server
{
listen 80;
server_name *.mynetwork.cn mynetwork.cn;
location / {
add_header backendIP $upstream_addr;
add_header backendCode $upstream_status;
proxy_pass http://192.168.9.101:9999;
}
access_log logs/mynetwork.cn.log;
}
http的单域名,多转发,使用location /的实现
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';access_log /var/log/nginx/access.log main;
error_log /var/log/nginx/error.log;
sendfile on;
#tcp_nopush on;keepalive_timeout 65;
#gzip on; include /etc/nginx/conf.d/*.conf;
server
{
listen 30001;
server_name *.xxx.com xxx.com;
location ^~/mq/ {
add_header backendIP $upstream_addr;
add_header backendCode $upstream_status;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://xxx:30002/;
}
access_log /var/log/nginx/mq.log;location ^~/es/ {
add_header backendIP $upstream_addr;
add_header backendCode $upstream_status;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://xxx:30001/;}
access_log /var/log/nginx/es.log;
}
}
测试,域名相同,请求不同
成功
正片开始
首先find / -name 找到nginx.conf,他一般在/etc/nginx的目录下面
开启socket核心就是加2行代码
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
这个是我原来的接口8087地址(server_name填写域名地址)
我的后端socket的地址是
ws://192.168.9.101:8087/openSocket
我想要的是当访问openSocket后,能够连接上
配置如下
location /openSocket {
add_header backendIP $upstream_addr;
add_header backendCode $upstream_status;
proxy_redirect off;
proxy_connect_timeout 6000;
proxy_read_timeout 6000;
proxy_send_timeout 6000;
proxy_set_header Host 192.168.9.101:8087;
proxy_pass http://192.168.9.101:8087/openSocket;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
把这个复制到nginx.conf的server的接口目录下
这个是其中http_upgrade的引用,放在与server同级的位置
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
替换/etc/nginx/nginx.conf
sudo nginx -s reload更新服务
重新打开网页客户端,进行连接
这个连接成功,是我服务端发送给客户端的文章来源:https://www.toymoban.com/news/detail-789467.html
文章来源地址https://www.toymoban.com/news/detail-789467.html
到了这里,关于nginx请求转发webSocket的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!