分享

Nginx代理显实真实IP的解决

 WindySky 2017-11-30

Nginx 是目前比较流行的 Web 服务器(当然它还能做其他的事情),我是因为使用 Tornado 开发 Web 应用程序而开始使用它的. 本文主要是我的使用过程中一些记录.

nginx 命令用法

选项 释义
-h 帮助
-s signal 向主线程发送一个信号以控制其行为, signal 值可以是 stop, quit, reopen, reload

用户及权限

Nginx 有个 user 配置命令可以设置用户及用户组:

语法:   user user [group]
缺省值: nobody nobody 

比如,我开发中使用 HOME 下的项目目录,因些我设置 nginx 使用的用户为 lijian , 在配置文件 (/etc/nginx/conf/nginx.conf) 中添加:

user lijian lijian;

启动 Nginx 后,查看进程可以看到:

$ ps aux|grep nginx
root      4300  0.0  0.0  36180  2036 ?        Ss   11:08   0:00 nginx: master process nginx
lijian    4436  0.0  0.0  36584  2092 ?        S    11:16   0:00 nginx: worker process

如何正确记录来源 IP

Nginx 做前端

这种情况下, Nginx 把真实 IP 保留在一个字段中,让后台的应用程序获取即可. nginx 配置示例 :

upstream ylinux_local {
    server 192.168.122.48:80;
}
server {
    listen 80;
    server_name ~^(www\.)?ylinux.org$ jianlee.ylinux.org;

    access_log  /opt/LuoYun/logs/ylinux.org.access.log;

    location / {
        proxy_read_timeout 1800;
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_pass http://ylinux_local;
    }
}

YLinux 的web是用 tornado 创建的,可以在里面启用 X-Real-IP 记录.

Nginx 级联

这种情况,前端是 Nginx , 后端又一个 Nginx , 再接应用程序 . (更多级联道理类似) . 前端 Nginx 配置和上面一样, 不用改变. 后端 Nginx 要使用它的 real-ip module .

注意: 和网上的大多数文章不一样 , 本文测式了 CentOS 6.4 x86_64 环境下, 仓库里安装的 nginx 己经默认编绎支持这个模块了 (可见多级 Nginx 配置还是非常流行的) , 请通过 nginx -V 命令查看你的 nginx 编绎配置. 如果有 --with-http_realip_module 选项, 表明此 nginx 己支持此用法. 否则,请自行编绎.

后端 nginx 配置如下:

upstream ylinux_local {
    server 127.0.0.1:8888;
}
server {
    listen 80;
    server_name ~^(www\.)?ylinux.org$;

    access_log  /srv/log/ylinux.org.access.log;

set_real_ip_from   192.168.122.0/24;
set_real_ip_from   192.168.122.1;
real_ip_header     X-Real-IP;

    location / {
        proxy_read_timeout 1800;
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_pass http://ylinux_local;
    }
}
    server {
        listen 80;
        server_name jianlee.ylinux.org;

        access_log  /srv/log/jianlee.ylinux.org.access.log;

        location / {
            root "/srv/YLinux/jianlee/";
            index index.html index.htm;
        }
    }

这三行才是重点:

set_real_ip_from   192.168.122.0/24;
set_real_ip_from   192.168.122.1;
real_ip_header     X-Real-IP;

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多