Nginx主配置文件如下,在主配置文件中需要添加$http_x_forwarded_for
日志格式
[root@abcdocker nginx-1.22.1]# cat conf/nginx.conf
user nginx;
error_log logs/nginx_error.log;
worker_processes 1;
events {
worker_connections 4096;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main ' $remote_addr | $http_x_forwarded_for | $remote_user | $time_local | $request | $http_host |'
' $status | $upstream_status | $body_bytes_sent | $http_referer '
' $http_user_agent | $upstream_addr | $request_time | $upstream_response_time';
...
日志格式中需要添加$http_x_forwarded_for
这里使用include引用子配置文件
include /opt/nginx-1.22.1/conf/conf.d/*.conf;
自配置文件如下
[root@abcdocker nginx-1.22.1]# cat conf/conf.d/nginx.conf
server {
listen 80;
server_name localhost;
access_log logs/access.log main; #需要添加日志引用
proxy_set_header X-Real-IP $remote_addr; #添加透传配置
proxy_set_header X-Forwarded-For $remote_addr; #添加透传配置
location / {
root html;
}
}
访问测试
架构图如下
访问Nginx页面
访问日志
192.168.0.6 | 168.138.171.206 | - | 15/Dec/2023:10:57:24 +0800 | GET / HTTP/1.1 | nginx.frps.fun | 200 | - | 615 | - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 | - | 0.000 | -
- 192.168.0.6 为apisix IP
- 168.138.171.206 PC IP,用户真实访问IP
如果我们前面没有apisix或者其它lb,也可以使用curl
命令来模拟X-Forwarded-For日志
[root@abcdocker nginx-1.22.1]# curl http://127.0.0.1/ -H 'X-Forwarded-For: 1.1.1.1' -v
* About to connect() to 127.0.0.1 port 80 (#0)
* Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 80 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.29.0
> Host: 127.0.0.1
> Accept: */*
> X-Forwarded-For: 1.1.1.1 #-v参数可以看到这里参数已经传入
>
< HTTP/1.1 200 OK
< Server: nginx
< Date: Fri, 15 Dec 2023 03:09:05 GMT
< Content-Type: text/html; charset=utf-8
< Content-Length: 615
< Last-Modified: Mon, 09 Oct 2023 06:03:57 GMT
< Connection: keep-alive
< ETag: "652397cd-267"
< Accept-Ranges: bytes
<
<!DOCTYPE html>
#http:127.0.0.1 就是Nginx服务器
日志输出如下
127.0.0.1 | 1.1.1.1 | - | 15/Dec/2023:11:05:56 +0800 | GET / HTTP/1.1 | 127.0.0.1 | 200 | - | 615 | - curl/7.29.0 | - | 0.000 | -
需要配置好日志格式,否则日志不输出!