nginx代理websocket支持wss访问

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了nginx代理websocket支持wss访问相关的知识,希望对你有一定的参考价值。

hanye.com.conf配置如下
 map $http_upgrade $connection_upgrade   
     default upgrade;  
     ‘ ‘ close;  
   
 upstream hanye   
     server 192.168.1.101:8888;
        server 192.168.1.102:8888;
   
 server   
     listen 8888;  
     server_name hanye.com;
     ssl on;
     ssl_certificate /etc/nginx/ssl/hanye.com.crt;
     ssl_certificate_key /etc/nginx/ssl/hanye.com.key;
     ssl_session_timeout 10m;
     ssl_buffer_size     64k;
     ssl_session_cache       shared:SSL:10m;
     ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
     ssl_protocols TLSv1 TLSv1.1 TLSv1.2 SSLv3;
     ssl_prefer_server_ciphers on;
     ssl_verify_client off;
              add_header Access-Control-Allow-Origin *;
      add_header Access-Control-Allow-Methods ‘GET, POST, OPTIONS‘;
      add_header Access-Control-Allow-Headers ‘DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization‘;
      if ($request_method = ‘OPTIONS‘) 
      return 204;
       
             include deny_host.conf;
      if (!-e $request_filename)
       rewrite (.*) /index.php last;
      
     location /   
         proxy_pass http://hanye;  
         proxy_http_version 1.1;  
         proxy_set_header Upgrade $http_upgrade;  
         proxy_set_header Connection "Upgrade";  
                     proxy_connect_timeout 300s;
         proxy_send_timeout 900;
         proxy_read_timeout 900;
         proxy_buffer_size 32k;
         proxy_buffers 4 64k;
         proxy_busy_buffers_size 128k;
         proxy_redirect off;
         proxy_hide_header Vary;
         proxy_set_header Accept-Encoding ‘‘;
         proxy_set_header Referer $http_referer;
         proxy_set_header Cookie $http_cookie;
         proxy_set_header Host $host;
         proxy_set_header X-Real-IP $remote_addr;
         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

      
     location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ 
       expires 30d;
       access_log off;
     
     location ~ .*\.(js|css)?$ 
       expires 7d;
       access_log off;
      
      location ~ /\.ht 
        deny all;
      
       


    map指令的作用:
  该作用主要是根据客户端请求中$http_upgrade 的值,来构造改变$connection_upgrade的值,即根据变量$http_upgrade的值创建新的变量$connection_upgrade,
   创建的规则就是里面的东西。其中的规则没有做匹配,因此使用默认的,即 $connection_upgrade 的值会一直是 upgrade。然后如果 $http_upgrade为空字符串的话,

那值会是 close。

192.168.1.101:8888和192.168.1.102:8888;是真正的服务端地址,nginx所在域名是hanye.com.conf,代理的端口号是8888,所以前端访问的时候这样配置:
WEBSOCKET_URL: ‘wss://hanye.com.conf:8888‘。

访问方式

技术图片

以上是关于nginx代理websocket支持wss访问的主要内容,如果未能解决你的问题,请参考以下文章

nginx ws怎么变成wss

Nginx配置之WSS

微信小程序 WebSocket 使用非 443 端口连接

WS转WSS协议

nginx配置websocket支持wss

实现Nginx代理WSS协议