websocket+前后端分离+https的nginx配置

后端服务路径:

     172.168.0.2:8080

     172.168.0.2:7080

前端目录(html + css + js):

      /root/apps/mzsg-web

1、修改 /etc/nginx.conf,注释掉nginx默认网站配置

        include /etc/nginx/conf.d/*.conf;

        #include /etc/nginx/sites-enabled/*;

 2、在/etc/nginx/conf.d目录下面新建配置文件,建议以网站简称全名,如mzsg.conf

    

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
upstream cat {
      server 172.168.0.2:8080 weight=5;
      server 172.168.0.2:7080 weight=5;
}
server{
   listen       80;
  server_name localhost;
  location / {
            proxy_pass http://cat;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header X-real-ip $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header APP_ID mzsg;
            proxy_set_header APP_KEY 31134314124fadfadf;
    }
 
  location ~ \.(html|js|css|png|gif|jpg)$ {
        root  /root/apps/mzsg-web;
            index  index.html index.htm;
  }
}

 如果是以.(html|js|css|png|gif|jpg)作为后缀的请求,则直接请求静态资源 /root/apps/mzsg-web 否则,转发给两个后端,这里两个后端负载策略采用了权重的方式,可以根据实际情况选择其它策略,如轮询、IP哈希、最小连接等

  proxy_set_header X-real-ip remoteaddr;proxysetheaderXForwardedForremoteaddr;proxysetheaderX−Forwarded−Forremote_addr;
  这两个HTTP头是因为采用了nginx作为代理后,后端可以通过 X-real-ip 或 X-Forwarded-For取得用户IP地址

  proxy_set_header APP_ID mzsg; proxy_set_header APP_KEY 31134314124fadfadf;
  这两个HTTP头是因为后端权限校验需要

    proxy_set_header Upgrade $http_upgrade;  proxy_set_header Connection "upgrade"; 
      声明支持websocket

3、支持SSL

修改前端websocket连接代码,原本ws://需要改为wss://(购买或)生成密钥和证书,过程省略。需要注意的是:自己生成的证书在很多浏览器上会报警告,忽略后websocket仍然能用,如Chrom、Firefox,但有些浏览器不能用,如Safari。修改/etc/nginx/conf.d/mzsg.conf

 

复制代码
upstream cat { 
      server 172.168.0.2:8080 weight=5; 
      server 172.168.0.2:7080 weight=5; 
}
server{
   listen 443;
    ssl on;
    ssl_certificate /etc/nginx/server.crt;
    ssl_certificate_key /etc/nginx/server.key;
  server_name localhost;
  location / {
            proxy_pass http://cat;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_set_header X-real-ip $remote_addr;
            proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header APP_ID mzsg;
            proxy_set_header APP_KEY 31134314124fadfadf;
    }

  location ~ \.(html|js|css|png|gif|jpg)$ {
        root  /root/apps/mzsg-web;
            index  index.html index.htm;
  }
}
posted @ 2018-01-18 09:20  追忆丶年华  阅读(637)  评论(0编辑  收藏  举报