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

    

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 $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

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;
  }
}

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM