在Nginx配置中,设置访问日志非常简单。你需要在http、server或location块中使用access_log指令。以下是一些示例:
http块中设置全局访问日志:http {
access_log /var/log/nginx/access.log;
...
}
server块中设置特定虚拟主机的访问日志:server {
...
access_log /var/log/nginx/example.com.access.log;
...
}
location块中设置特定路径的访问日志:server {
...
location /example/ {
access_log /var/log/nginx/example.access.log;
...
}
...
}
你还可以使用log_format指令自定义访问日志的格式。例如,创建一个名为main的自定义格式:
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
...
}
在这个例子中,我们定义了一个包含远程地址、用户、时间、请求、状态码、发送的字节数、引用页、用户代理和X-Forwarded-For头的日志格式。
最后,不要忘记重启Nginx以使更改生效:
sudo nginx -t # 检查配置文件语法是否正确
sudo nginx -s reload # 重新加载配置文件
现在,Nginx将按照你的配置记录访问日志。