Nginx 常用配置速查
本文汇总 Nginx 日常使用的高频配置项,包含日志输出与 gzip 压缩两个主题。
版本说明
本文基于多篇历史文章合并整理,首次发布于 2019-11(用户字段记录),2020-10(gzip 压缩)曾做修订。合并后版本写于 2026-09。
按 D1 速查体裁登记豁免。
# 1. 使用 $remote_user 字段记录访问用户
在企业内网环境中,给没有集成权限认证系统的页面加一层认证后,如果使用 NGINX 统一账号,出了问题难以定位是谁操作的。通过在日志中添加 $remote_user 字段,可以记录访问者的身份。
# 1.1 配置示例
在日志格式中添加用户字段:
log_format json escape=json '{ "remote_addr": "$remote_addr",'
'"@timestamp":"$time_iso8601",'
'"request_uri": "$request_uri",'
'"remote_user": "$remote_user",' # 写入之后,就能记录访问的用户了
'"verb": "$request_method",'
'"httpversion": "$server_protocol",'
'"response": "$status", '
'"body_bytes_sent": "$body_bytes_sent", '
'"user_agent": "$http_user_agent", '
'"server_name": "$host",'
'"request_time": "$request_time" }';
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
然后结合 LDAP 认证模块配置(参考相关文档),日志中即可看到用户名:
{ "remote_addr": "127.0.0.1", "@timestamp": "2019-11-15T16:57:29+08:00", "request_uri": "/", "remote_user": "eryajf", ... }
1
# 1.2 适用场景
- 内部系统审计
- 问题溯源
- 访问统计按用户分组
# 2. nginx 配置 gzip 压缩
gzip 压缩可以显著减少传输数据量,提升页面加载速度。
# 2.1 基础配置
在 http 区块添加:
gzip on;
gzip_comp_level 4;
gzip_static on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_proxied any;
gzip_types text/plain application/xml application/javascript text/css application/json image/jpeg image/gif image/png;
gzip_disable "MSIE [1-5]\\.";
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 2.2 常见问题
配置后不生效?
检查请求的 Content-Type 是否在 gzip_types 列表中。例如 application/javascript 需要显式添加:
gzip_types text/plain application/xml application/javascript application/x-javascript text/css application/json image/jjpeg image/gif image/png;
1
# 2.3 验证方法
- 浏览器开发者工具 → Network → 查看 Response Headers 中是否有
Content-Encoding: gzip - 使用 curl 验证:
curl -I -H "Accept-Encoding: gzip" http://example.com/
1
# 3. 参考
上次更新: 9/4/2026