Nginx 配置中·IP地址变量

发布于:2025-06-17 ⋅ 阅读:(17) ⋅ 点赞:(0)

在Nginx配置中,有时需要使用到IP地址变量,比如在访问日志中记录客户端的IP地址,或者在根据IP地址的不同进行不同的配置处理。Nginx提供了几种方式来获取和使用IP地址变量。

1. 使用$remote_addr变量

$remote_addr是Nginx内置的变量,用来获取客户端的IP地址。这是最直接的方法,适用于大多数情况。

server {
    listen 80;
    server_name example.com;
 
    location / {
        # 使用$remote_addr获取客户端IP
        access_log /var/log/nginx/access.log combined;
    }
}

2. 使用$http_x_forwarded_for变量

如果你的服务器部署在反向代理(如Nginx或HAProxy)后面,客户端的真实IP地址可能会被代理服务器的IP地址所覆盖。在这种情况下,可以使用$http_x_forwarded_for变量来获取原始的客户端IP地址。这个变量通常在HTTP请求头X-Forwarded-For中设置。

server {
    listen 80;
    server_name example.com;
 
    location / {
        # 使用$http_x_forwarded_for获取原始客户端IP
        real_ip_header X-Forwarded-For;
        set_real_ip_from 0.0.0.0/0; # 或者指定具体的代理服务器IP段
        access_log /var/log/nginx/access.log combined;
    }
}

3. 使用real_ip模块设置原始IP地址

如果你在使用反向代理,并且希望在Nginx中直接设置原始IP地址,可以使用real_ip模块。首先确保你的Nginx编译时包含了real_ip模块。

load_module modules/ngx_http_realip_module.so; # 如果是在编译时未包含此模块的话需要取消注释并确保模块路径正确

然后在配置文件中使用:

http {
    real_ip_header X-Forwarded-For; # 指定用于传递原始IP的HTTP头
    set_real_ip_from   0.0.0.0/0;   # 允许所有IP,或者指定代理服务器的IP段
 
    server {
        listen 80;
        server_name example.com;
 
        location / {
            # 现在可以使用$remote_addr获取原始客户端IP
            access_log /var/log/nginx/access.log combined;
        }
    }
}

4. 使用map指令自定义变量

如果你需要根据不同的IP地址应用不同的配置,可以使用map指令来创建自定义的变量。

http {
    map $remote_addr $custom_ip {
        192.168.1.1  "internal"; # 内部IP地址的标识符
        default      "external"; # 其他IP地址的标识符
    }
 
    server {
        listen 80;
        server_name example.com;
 
        location / {
            # 根据自定义的$custom_ip变量应用不同的配置或处理逻辑
            if ($custom_ip = "internal") {
                # 处理内部请求的逻辑
            }
            access_log /var/log/nginx/access.log combined;
        }
    }
}

以上方法可以根据你的具体需求选择使用。如果你在使用反向代理,推荐使用real_ip模块或$http_x_forwarded_for变量来获取原始客户端的IP地址。


网站公告

今日签到

点亮在社区的每一天
去签到