Windows环境用Nginx配置反向代理和负载均衡

引言:在前后端分离架构下,难免会遇到跨域问题。目前的解决方案大致有JSONP,反向代理,CORS这三种方式。JSONP兼容性良好,最大的缺点是只支持GET方式请求。反向代理方式简单彻底,基本只需要服务器配置即可完成。CORS由服务提供程序主动声明自己可信任源,目前的缺点是老式浏览器无法支持。

问题:反向代理如何实现?

解决方案:使用Nginx轻松搞定反向代理。配置很简单,还附带负载均衡配置方法。

步骤1.下载Nginx。最新下载地址:http://nginx.org/en/download.html

步骤2.修改/ conf/ nginx.conf配置文件。Nginx运行起来。

 

访问localhost:8000/index.html会直接访问发布的静态文件。访问localhost:8000/api/index.html会被轮询分配到localhost:8005/index.html和localhost:8006/index.html。这样就能保证前端和后端服务在同源下,彻底解决跨域问题。同时api还实现了负载均衡,减轻了服务器压力。

步骤3,设置服务端cookie的path和domain。

效果:

 

涉及配置文件内容: 

 #设定负载均衡的服务器列表
         #weight越大,负载的权重就越大。8006的访问量是8005的两倍
         upstream targetserver{
                   #ip_hash;#按访问ip的hash结果分配,解决Session跨服务器问题
                   server localhost:8005 weight=1; 
                   server localhost:8006 weight=2; 
         }
 
location ^~ /api/ {
            #proxy_pass    http:
// localhost:8006;#反向代理方式1
            proxy_pass  http: // targetserver; #反向代理2,也可做负载均衡。
            #proxy_redirect default ;
            proxy_redirect off ;
            proxy_set_header Host $host;
            proxy_set_header X
-Real- IP $remote_addr;
            proxy_set_header REMOTE
- HOST $remote_addr;
            proxy_set_header X
-Forwarded- For $proxy_add_x_forwarded_for;
            client_max_body_size 50m;
            client_body_buffer_size 256k;
            proxy_connect_timeout
30 ;
            proxy_send_timeout
30 ;
            proxy_read_timeout
60 ;
            proxy_buffer_size 256k;
            proxy_buffers
4 256k;
            proxy_busy_buffers_size 256k;
            proxy_temp_file_write_size 256k;
            proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
            proxy_max_temp_file_size 128m;                           

            rewrite
/api/(.+)$ /$ 1 break;#将/api/ 后面的路由直接转发到目标服务器的根目录
        }

                 

  location
/ {
              autoindex on;
        index index.html index.htm;
              root 
" E:\02源代码管理\技术文档\AngularJsDemo " ;   
        }

----------------------------------------------------正文结束分割线---------------------------------------------------- 

upstream还可以为每个设备设置状态值,这些状态值的含义分别如下:

down 表示单前的server暂时不参与负载.

weight 默认为1.weight越大,负载的权重就越大。

max_fails :允许请求失败的次数默认为1.当超过最大次数时,返回proxy_next_upstream 模块定义的错误.

fail_timeout : max_fails次失败后,暂停的时间。

backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。

猜你喜欢

转载自www.linuxidc.com/Linux/2017-01/139038.htm