原由
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更新服务
重新打开网页客户端,进行连接
这个连接成功,是我服务端发送给客户端的
版权归原作者 我要用代码向我喜欢的女孩表白 所有, 如有侵权,请联系我们删除。