nginx:反向代理

1 nginx反向代理

正向代理浏览器,反向代理web服务器
默认80端口,ip地址xxx.xx.xxx.xxx
 
server {
         listen       80;
         server_name  localhost;
         client_max_body_size 2m;
 
        location /static {
          root /data/www/helloworld;
        }
 
        location / {
            proxy_pass http://127.0.0.1:8000/;
        }    
 }

 

2 代理转发方式

第一种:
location / {
    proxy_pass http://127.0.0.1:8000/;
}
代理到URL:http://xxx.xx.xxx.xxx:8000/index.html
访问URL:http://demo.adamant.com/

第二种(相对于第一种,最后少一个 / )
location /api/ {
    proxy_pass http://127.0.0.1:8000;
}
代理到URL:http://xxx.xx.xxx.xxx/api/index.html
访问URL:demo.adamant.com/api
第三种:
location /api/admin/ {
    proxy_pass http://127.0.0.1:8000;
}
代理到URL:http://xxx.xx.xxx.xxx/api/admin/index.html
访问URL:demo.adamant.com/api/admin

3 参数解析

server {
         listen       80;
         server_name  localhost;
         client_max_body_size 2m;

        location /static {
          root /data/www/pro_base;
        }

        location /api/ {
            proxy_pass http://127.0.0.1:8000/;
        }

        location /api/admin/ {
            proxy_pass http://127.0.0.1:8080/;

            proxy_http_version 1.1;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header Host $host;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
        }

        location / { try_files $uri @probase; }
        location @probase {
            include uwsgi_params;
            uwsgi_pass unix:/tmp/probase.sock;
        }
}

 

(1)IP地址处理

在实际应用中,我们可能需要获取用户的ip地址,比如做异地登陆的判断,或者统计ip访问次数等,通常情况下我们使用request.getRemoteAddr()等类似方法就可以获取到客户端ip,但是当我们使用了nginx作为反向代理后,使用request.getRemoteAddr()获取到的就一直是nginx服务器的ip的地址,那这时应该怎么办?

由于在客户端和web服务器之间增加了中间层,因此web服务器无法直接拿到客户端的ip,通过$remote_addr变量拿到的将是反向代理服务器的ip地址。

如果我们想要在web端获得用户的真实ip,就必须在nginx这里作一个赋值操作

proxy_set_header            X-real-ip $remote_addr;

在web端可以类似这样获取:request.getAttribute("X-real-ip”)

 

proxy_set_header            X-Forwarded-For $proxy_add_x_forwarded_for;

意思是增加一个$proxy_add_x_forwarded_for到X-Forwarded-For里去,注意是增加,而不是覆盖,当然由于默认的X-Forwarded-For值是空的,所以我们总感觉X-Forwarded-For的值就等于$proxy_add_x_forwarded_for的值,实际上当你搭建两台nginx在不同的ip上,并且都使用了这段配置,那你会发现在web服务器端通过request.getAttribute("X-Forwarded-For")获得的将会是客户端ip和第一台nginx的ip。

假设有两台nginx转发,通过这个赋值以后现在的X-Forwarded-For的值就变成了“用户的真实ip,第一台nginx的ip”

 

 

 

 


 
 
 
 
posted @ 2018-05-28 11:45  Adamanter  阅读(93)  评论(0编辑  收藏  举报