Nginx基础access_log配置核心是设置路径、格式与开关状态:在http/server块中写access_log /var/log/nginx/access.log combined;,确保路径可写、语法正确并重载生效;可自定义log_format后引用;用access_log off;关闭特定location日志;需配合logrotate实现日志轮转。

在 Nginx 中配置基础的 access_log,核心是设置日志路径、格式和开关状态。默认情况下 Nginx 已启用访问日志,但你可能需要自定义路径、格式或关闭某些 location 的记录。
1. 全局或 server 块中启用并指定日志路径
最常用的方式是在 http、server 或 location 块中使用 access_log 指令:
-
语法:
access_log path [format [buffer=size] [gzip[=level]] [flush=time] [if=condition]]; -
基础示例(写入
/var/log/nginx/access.log,使用默认combined格式):access_log /var/log/nginx/access.log combined; - 如果省略格式名,默认使用
log_format定义的combined(Nginx 内置)
2. 自定义日志格式(可选但推荐)
用 log_format 定义新格式,再在 access_log 中引用:
将 WCAG 2 AA 无障碍标准应用于设计系统、UI 组件和网页——通过可运行的验证器进行对比度计算,采用设计 token 模式使颜色天生可访问,设定排版和焦点状态规则,并提供语义检查清单。适用于构建或审查 UI。
- 在
http块中添加(不能放在 server 内):log_format myformat '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" $request_time'; - 然后在 server 或 location 中启用:
access_log /var/log/nginx/myapp.log myformat; - 常用变量:
$remote_addr(客户端 IP)、$request(请求行)、$status(HTTP 状态码)、$request_time(处理耗时,单位秒,精度毫秒)
3. 关闭特定 location 的访问日志
有些静态资源(如 favicon、图片)不需要记录,节省 I/O 和磁盘空间:
location = /favicon.ico { access_log off; }location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { access_log off; }- 注意:
access_log off;是显式关闭,不是注释掉该行
4. 日志切割与维护建议
Nginx 本身不自动轮转日志,需配合外部工具(如 logrotate):
- 典型 logrotate 配置片段(
/etc/logrotate.d/nginx):/var/log/nginx/*.log {<br> daily<br> missingok<br> rotate 52<br> compress<br> delaycompress<br> notifempty<br> create 0644 www-data www-data<br> sharedscripts<br> postrotate<br> if [ -f /var/run/nginx.pid ]; then<br> kill -USR1 `cat /var/run/nginx.pid`<br> fi<br> endscript<br>} -
kill -USR1通知 Nginx 重新打开日志文件(实现无缝切换)
配置完记得测试语法:nginx -t,再重载生效:nginx -s reload。日志文件路径需确保 Nginx 工作进程(通常是 www-data 或 nginx 用户)有写权限。

















