Nginx 常见问题:

1.Nginx 启动/重启失败:

现象:执行 nginx -s reloadsystemctl restart nginx报错

nginx -t

常见原因

  • 缺少分号 ;

  • 括号 {}不匹配

  • server_nameroot路径错误

 端口被占用:

现象:bind() to 0.0.0.0:80 failed (98: Address already in use)

查看占用端口的进程:

lsof -i :80
# 或
netstat -tunlp | grep :80

杀掉占用进程或修改 Nginx 监听端口

2、403 Forbidden 错误

常见原因

  1. 目录/index 文件不存在

    • 未配置 index index.html index.htm;

    • 根目录没有默认首页文件

  2. 权限不足

chmod -R 755 /path/to/webroot
chown -R nginx:nginx /path/to/webroot

3、404 Not Found 错误

路径配置错误,location匹配不正确,静态资源确实不存在

4、Nginx 反向代理问题

     确保后端服务正常启动

     可使用 curl http://127.0.0.1:8080测试

 5.Nginx 高并发下性能问题

worker_processes auto;
worker_connections 10240;

keepalive_timeout 65;
sendfile on;
gzip on;

增加性能

日志观察:

tail -f /var/log/nginx/error.log

状态码:

Nginx 常见的状态码主要沿用了 HTTP 标准状态码,同时也有一些 Nginx 特有的错误码。下面按类别梳理一下最常见、最需要关注的:

一、1xx 信息性状态码(较少见)

100 Continue:客户端继续发送请求体

101 Switching Protocols:协议切换(如 WebSocket)

二、2xx 成功

200 OK:请求成功

201 Created:资源创建成功

204 No Content:成功但无返回内容

三、3xx 重定向

301 Moved Permanently:永久重定向

302 Found:临时重定向

304 Not Modified:资源未修改(缓存生效)

四、4xx 客户端错误(非常常见)

400 Bad Request:请求语法错误或非法

401 Unauthorized:未认证(如未登录)

403 Forbidden:服务器拒绝访问(权限不足、IP 限制等)

404 Not Found:资源不存在

405 Method Not Allowed:请求方法不被允许(GET/POST 等)

408 Request Timeout:请求超时

413 Payload Too Large:上传文件过大(client_max_body_size)

414 URI Too Long:请求 URL 过长

429 Too Many Requests:限流(limit_req)

五、5xx 服务端错误(重点排查对象)

500 Internal Server Error:服务器内部错误(后端异常)

501 Not Implemented:不支持的请求方式

502 Bad Gateway:非常常见,上游服务(PHP/Java/Node)无响应或报错

503 Service Unavailable:服务暂时不可用(过载、维护)

504 Gateway Timeout:上游服务超时(fastcgi/proxy 超时)

505 HTTP Version Not Supported

六、Nginx 特有 / 常见扩展场景

虽然严格来说仍是 HTTP 状态码,但在 Nginx 中很典型:

444:Nginx 内部使用,直接关闭连接(不返回响应头)

499:客户端主动断开连接(Nginx 特有,很常见)

400​ 也常出现在:

请求头过大

非法字符

HTTP 协议错误

七、排查时的小经验

502/504:重点看 upstream、fastcgi、proxy 配置和后端日志

403:检查目录权限、SELinux、allow/deny 规则

413:调整 client_max_body_size

499:通常是前端提前取消请求或网络问题

Nginx压力测试和处理:

ab(Apache Bench,简单快速)

ab -n 10000 -c 200 http://localhost/

-n总请求数

-c并发数

适合:快速摸底 QPS

wrk(推荐,高性能)
bash
wrk -t4 -c200 -d30s http://localhost/

-t线程数

-c连接数

-d持续时间

适合:高并发、长连接、更接近真实流量

压力大怎么做:
 

worker 进程数不合理

worker_processes auto;   # 一般 = CPU 核数
worker_cpu_affinity auto;

worker_connections 太小

events {
    worker_connections 65535;
}

后端问题:

proxy_pass http://backend;
proxy_connect_timeout 3s;
proxy_read_timeout 10s;
proxy_send_timeout 10s;

proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;

keepalive :

upstream backend {
    server 127.0.0.1:8080;
    keepalive 32;
}

location / {
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_pass http://backend;
}

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐