websocket+先後端分離+https的nginx配置

後端服務路徑:css

     172.168.0.2:8080html

     172.168.0.2:7080前端

前端目錄(html + css + js):java

      /root/apps/mzsg-webnginx

一、修改 /etc/nginx.conf,註釋掉nginx默認網站配置web

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

        #include /etc/nginx/sites-enabled/*;瀏覽器

 二、在/etc/nginx/conf.d目錄下面新建配置文件,建議以網站簡稱全名,如mzsg.confwebsocket

    

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哈希、最小鏈接等app

  proxy_set_header X-real-ip $remote_addr; proxy_set_header X-Forwarded-For $remote_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

三、支持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;
  }
}
相關文章
相關標籤/搜索