# nginx.cc — full text for language models

> Unofficial. Not affiliated with F5, Inc. or the NGINX project. NGINX is a trademark of F5, Inc. Version 0.14.1, updated 2026-12-02. Index: https://nginx.cc/llms.txt. Please cite the page URL given under each entry.

Each entry: short answer (cause → fix → config), typical log lines, causes, diagnosis commands, fixes, key facts with their sources, FAQ. Facts were checked against the linked pages on the date shown.

## Error encyclopedia (English)

### Nginx 502 Bad Gateway: causes and fixes
Page: https://nginx.cc/en/errors/502-bad-gateway · Last verified: 2026-11-14

**Short answer:** 502 means nginx could not reach or understand the backend (PHP-FPM, Node, a Docker container…). Check: is the backend running → do address and port match → permissions/SELinux → oversized response headers.
**Most common cause:** The backend is not running, crashed, or was OOM-killed.
**Try this first:** Match the backend's listen address
```nginx
location / {
    proxy_pass http://127.0.0.1:3000;   # do not use localhost
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
```

#### Typical log lines
```
connect() failed (111: Connection refused) while connecting to upstream
connect() to unix:/run/php/php8.3-fpm.sock failed (2: No such file or directory)
upstream sent too big header while reading response header from upstream
no live upstreams while connecting to upstream
```
#### Common causes
1. The backend is not running, crashed, or was OOM-killed.
2. Wrong address, port or socket path in proxy_pass / fastcgi_pass (the socket name changes after PHP upgrades).
3. Backend listens on 127.0.0.1 but proxy_pass uses localhost, which resolves to ::1; or a container only listens inside its network.
4. SELinux blocks nginx from making network connections (common on CentOS/Rocky/Alma).
5. Backend response headers too large (big cookies/JWT) for proxy_buffer_size.
#### Diagnosis commands
- `tail -n 50 /var/log/nginx/error.log` — See which connect() failure it is
- `ss -ltnp | grep -E ':3000|php-fpm'` — Confirm the backend is listening
- `curl -sv http://127.0.0.1:3000/ -o /dev/null` — Hit the backend directly, bypassing nginx
- `ls -l /run/php/` — The real PHP-FPM socket name
- `systemctl status php8.3-fpm --no-pager` — Backend service state
- `getenforce && getsebool httpd_can_network_connect` — Is SELinux blocking it
#### Fix configs
PHP-FPM socket path:
```nginx
location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;   # must match ls /run/php/
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
```
Oversized response headers:
```nginx
proxy_buffer_size 16k;
proxy_buffers 8 16k;
# PHP-FPM:
fastcgi_buffer_size 32k;
fastcgi_buffers 16 16k;
```
Allow under SELinux (RHEL family):
```nginx
setsebool -P httpd_can_network_connect 1
```
#### Key facts and sources
- proxy_buffer_size defaults to one memory page (4k or 8k); response headers that do not fit cause “upstream sent too big header”. Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffer_size
- proxy_connect_timeout defaults to 60s and usually cannot exceed 75 seconds. Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_connect_timeout
- fastcgi_pass accepts a TCP address or a unix: socket path. Source: https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_pass
#### FAQ
- **What is the difference between 502 and 504?** 502 means the connection failed or the reply was invalid, usually instantly; 504 means the backend accepted but did not answer in time, usually after tens of seconds.
- **Does restarting nginx fix a 502?** Rarely. A 502 is almost always the backend; read the connect() error in error.log, then restart or fix the backend.
- **I get 502 behind Cloudflare. What now?** Check whose error page it is. A Cloudflare-styled 502 means Cloudflare cannot reach your origin (firewall, port); an nginx-styled one is the backend issue described here.

### Nginx 504 Gateway Timeout: causes and fixes
Page: https://nginx.cc/en/errors/504-gateway-timeout · Last verified: 2026-11-14

**Short answer:** 504 means the backend did not answer within nginx's timeout. Find what is slow first (queries, external APIs, queues), then raise proxy_read_timeout or fastcgi_read_timeout only as needed.
**Most common cause:** Slow backend work: slow SQL, a hung external API, long exports/uploads.
**Try this first:** Longer timeouts only where needed
```nginx
location /api/export {
    proxy_pass http://127.0.0.1:3000;
    proxy_connect_timeout 5s;
    proxy_read_timeout 300s;
    proxy_send_timeout 300s;
}
```

#### Typical log lines
```
upstream timed out (110: Connection timed out) while reading response header from upstream
upstream timed out (110: Connection timed out) while connecting to upstream
```
#### Common causes
1. Slow backend work: slow SQL, a hung external API, long exports/uploads.
2. PHP-FPM pool exhausted (pm.max_children too low) so requests queue.
3. proxy_read_timeout / fastcgi_read_timeout too short (default 60s).
4. Network path to the upstream is broken, so the connect phase times out.
#### Diagnosis commands
- `grep 'upstream timed out' /var/log/nginx/error.log | tail` — Connecting or reading phase?
- `time curl -s -o /dev/null http://127.0.0.1:3000/slow-path` — Time the backend directly
- `grep -i 'max_children' /var/log/php*-fpm.log` — Did PHP-FPM hit its process limit
#### Fix configs
PHP-FPM:
```nginx
location ~ \.php$ {
    fastcgi_read_timeout 300s;
    ...
}
# also tune max_execution_time in php.ini and pm.max_children in FPM
```
#### Key facts and sources
- proxy_read_timeout defaults to 60s and applies between two successive reads, not to the whole response. Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_read_timeout
- fastcgi_read_timeout also defaults to 60s. Source: https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_read_timeout
#### FAQ
- **Can I just set a huge timeout?** It stops the bleeding but not the cause. Long-held connections tie up workers; long jobs belong in an async queue with polling.
- **Is Cloudflare 524 the same as 504?** Similar. 524 is Cloudflare waiting over 100 s (free plan) for your origin; raising nginx timeouts will not help, the request must finish within 100 s.

### Nginx 413 Request Entity Too Large: upload size fix
Page: https://nginx.cc/en/errors/413-request-entity-too-large · Last verified: 2026-11-14

**Short answer:** 413 means the request body exceeded client_max_body_size (default only 1 MB). Raise it in http, server or location; for PHP also raise upload_max_filesize and post_max_size.
**Most common cause:** client_max_body_size not set; default 1m.
**Try this first:** Raise the limit
```nginx
server {
    client_max_body_size 100m;   # 0 disables the limit (not recommended)
}
```

#### Typical log lines
```
client intended to send too large body: 5242880 bytes
```
#### Common causes
1. client_max_body_size not set; default 1m.
2. The setting lives in another server/location the request does not hit.
3. PHP's upload_max_filesize / post_max_size is smaller (then PHP errors, not always 413).
4. A CDN or panel proxy in front has its own limit (Cloudflare free: 100 MB).
#### Diagnosis commands
- `nginx -T 2>/dev/null | grep -n client_max_body_size` — Where and what it is set to
- `grep 'too large body' /var/log/nginx/error.log | tail -3` — Confirm nginx rejected it
- `php -i | grep -E 'upload_max_filesize|post_max_size'` — PHP limits
#### Fix configs
Only for the upload endpoint:
```nginx
location /upload {
    client_max_body_size 500m;
    proxy_request_buffering off;   # stream large uploads
    proxy_pass http://127.0.0.1:3000;
}
```
PHP side:
```nginx
; php.ini
upload_max_filesize = 100M
post_max_size = 100M
; then systemctl restart php8.3-fpm
```
#### Key facts and sources
- client_max_body_size defaults to 1m; 0 disables the check; exceeding it returns 413. Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size
- PHP defaults: upload_max_filesize = 2M, post_max_size = 8M. Source: https://www.php.net/manual/en/ini.core.php
#### FAQ
- **Do I need to restart?** After nginx -t passes, systemctl reload nginx is enough. PHP changes need a PHP-FPM restart.
- **Which block should it go in?** http, server or location; inner overrides outer. Set a sane value per server and raise it on upload endpoints.

### Nginx 403 Forbidden: causes and fixes
Page: https://nginx.cc/en/errors/403-forbidden · Last verified: 2026-11-14

**Short answer:** 403 usually means no index file in a directory, file permissions nginx cannot read, a deny rule, or SELinux. Check whether error.log says “directory index forbidden” or “Permission denied”.
**Most common cause:** A directory was requested with no file matching index, and autoindex is off.
**Try this first:** Add index or use try_files
```nginx
root /var/www/site;
index index.html index.php;
location / {
    try_files $uri $uri/ =404;   # 404 instead of 403 when there is no index
}
```

#### Typical log lines
```
directory index of "/var/www/site/" is forbidden
open() "/var/www/site/index.html" failed (13: Permission denied)
access forbidden by rule
```
#### Common causes
1. A directory was requested with no file matching index, and autoindex is off.
2. The nginx user (www-data / nginx) lacks read/execute permission on the file or any parent directory.
3. Site lives under /root or /home/user whose permissions are 700.
4. A deny all / allow rule or auth matched.
5. Wrong SELinux file context (not httpd_sys_content_t).
#### Diagnosis commands
- `tail -n 20 /var/log/nginx/error.log` — index forbidden vs Permission denied
- `namei -l /var/www/site/index.html` — Permissions of every path component
- `sudo -u www-data cat /var/www/site/index.html >/dev/null && echo ok` — Read as the nginx user (use nginx on RHEL)
- `ls -Z /var/www/site` — SELinux context
#### Fix configs
Fix permissions:
```nginx
chown -R www-data:www-data /var/www/site     # nginx:nginx on RHEL
find /var/www/site -type d -exec chmod 755 {} +
find /var/www/site -type f -exec chmod 644 {} +
```
SELinux context:
```nginx
semanage fcontext -a -t httpd_sys_content_t '/var/www/site(/.*)?'
restorecon -Rv /var/www/site
```
#### Key facts and sources
- index checks the listed files in order; the default is only index.html (PHP sites must add index.php). Source: https://nginx.org/en/docs/http/ngx_http_index_module.html#index
- allow / deny rules are checked in order until the first match. Source: https://nginx.org/en/docs/http/ngx_http_access_module.html#allow
#### FAQ
- **Will chmod 777 fix 403?** Sometimes, but it is dangerous: any process can modify your site. Use 755 for dirs, 644 for files, owned by the deploy or nginx user.
- **Why is a site under /root always 403?** /root is 700, so the nginx user cannot even enter it. Move the site to /var/www.

### Nginx 404 and try_files: rewrites, SPA routes, root vs alias
Page: https://nginx.cc/en/errors/404-try-files · Last verified: 2026-11-14

**Short answer:** 404 although the file exists is usually a wrong root/alias path, or WordPress / Vue / React routes not falling back to the entry file with try_files.
**Most common cause:** root appends the full URI: root /var/www/static + /static/a.js = /var/www/static/static/a.js.
**Try this first:** SPA (Vue/React)
```nginx
location / {
    try_files $uri $uri/ /index.html;
}
```

#### Typical log lines
```
open() "/usr/share/nginx/html/about" failed (2: No such file or directory)
"/var/www/site/static/static/app.js" is not found (2: No such file or directory)
```
#### Common causes
1. root appends the full URI: root /var/www/static + /static/a.js = /var/www/static/static/a.js.
2. alias and location trailing slashes do not match.
3. SPA client routes (/about) are not real files on refresh.
4. WordPress permalinks lack try_files … /index.php?$args.
5. The request hit a different server block (server_name mismatch → default_server).
#### Diagnosis commands
- `tail -n 20 /var/log/nginx/error.log` — See the exact path nginx tried
- `nginx -T 2>/dev/null | grep -nE 'server_name|root|alias|try_files'` — Check effective root/alias
- `curl -sI -H 'Host: example.com' http://127.0.0.1/about` — Confirm which site answers
#### Fix configs
WordPress / Laravel:
```nginx
location / {
    try_files $uri $uri/ /index.php?$args;
}
```
root vs alias done right:
```nginx
# file at /var/www/static/a.js, requested as /static/a.js
location /static/ {
    alias /var/www/static/;    # trailing slash on both sides
}
# or
location /static/ {
    root /var/www;             # root excludes the location prefix
}
```
#### Key facts and sources
- try_files checks files in order; the last parameter is the fallback URI or =code. Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#try_files
- alias replaces the matched location part; root appends the whole URI. Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#alias
#### FAQ
- **What is special about try_files' last parameter?** Earlier parameters are file lookups; the last is the fallback: a status like =404 or an internal redirect URI like /index.html.
- **alias or root?** Use root when the directory matches the URL prefix, alias when it does not. Mind alias trailing slashes; a mismatch can allow path traversal.

### ERR_TOO_MANY_REDIRECTS with nginx: how to fix
Page: https://nginx.cc/en/errors/too-many-redirects · Last verified: 2026-11-14

**Short answer:** “Too many redirects” is most often a CDN fetching your origin over HTTP while the origin redirects HTTP to HTTPS, forever. Next come www↔apex ping-pong and the app and nginx both redirecting.
**Most common cause:** Cloudflare SSL mode Flexible: CDN fetches over HTTP, nginx 301s to HTTPS, CDN fetches over HTTP again…
**Try this first:** Redirect once, on port 80 only
```nginx
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://example.com$request_uri;
}
```

#### Typical log lines
```
rewrite or internal redirection cycle while internally redirecting to "/index.html"
```
#### Common causes
1. Cloudflare SSL mode Flexible: CDN fetches over HTTP, nginx 301s to HTTPS, CDN fetches over HTTP again…
2. Both www→apex and apex→www exist (nginx one way, the app or CDN rule the other).
3. WordPress siteurl disagrees with nginx; or X-Forwarded-Proto is missing so the app thinks it is HTTP and redirects again.
4. The try_files fallback file does not exist, causing an internal redirect cycle.
#### Diagnosis commands
- `curl -sIL --max-redirs 10 http://example.com | grep -iE '^(HTTP|location)'` — Print the whole redirect chain
- `curl -sI -H 'Host: example.com' http://127.0.0.1/` — See the origin's own redirect, bypassing the CDN
- `curl -sIL --max-redirs 10 https://example.com/ | grep -iE '^(HTTP|location)'` — See where the redirect chain loops
#### Fix configs
Tell the backend the real scheme:
```nginx
proxy_set_header X-Forwarded-Proto $scheme;
# behind Cloudflare with SSL=Full, $scheme is https
```
Cloudflare setting:
```nginx
# SSL/TLS → Overview → set the encryption mode to Full (strict)
# the origin needs a valid certificate (Cloudflare Origin CA works)
```
#### Key facts and sources
- Cloudflare's Flexible mode connects to the origin over HTTP; an origin that redirects HTTP to HTTPS then loops. Source: https://developers.cloudflare.com/ssl/origin-configuration/ssl-modes/flexible/
- return 301 / 302 stops processing and sends the redirect. Source: https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#return
#### FAQ
- **Does clearing the browser cache help?** 301s are cached, so after fixing try a private window. The root cause still has to be fixed server-side.
- **Fixed it, but the browser still loops?** Browsers cache 301 redirects, so the old one may linger. Verify in a private window or with curl -I, and clear the site's cache and cookies if needed.

### Nginx SSL handshake failed: troubleshooting
Page: https://nginx.cc/en/errors/ssl-handshake-failed · Last verified: 2026-11-14

**Short answer:** SSL handshake failures usually come from a cert without the full chain, a cert/key mismatch, port 443 without the ssl parameter, too old/new protocols or ciphers, or SNI mismatch from a CDN.
**Most common cause:** ssl_certificate points to cert.pem instead of fullchain.pem; some clients miss the intermediate.
**Try this first:** Standard HTTPS block
```nginx
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name example.com;
    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_session_cache shared:SSL:10m;
}
```

#### Typical log lines
```
SSL_do_handshake() failed (SSL: error:0A00010B:SSL routines::wrong version number)
SSL_CTX_use_PrivateKey("/etc/ssl/private/key.pem") failed (SSL: error:05800074:x509 certificate routines::key values mismatch)
peer closed connection in SSL handshake while SSL handshaking to upstream
```
#### Common causes
1. ssl_certificate points to cert.pem instead of fullchain.pem; some clients miss the intermediate.
2. Certificate and key do not match (only one was replaced on renewal).
3. listen 443 lacks ssl, so nginx speaks plain HTTP on 443 (wrong version number).
4. Only TLSv1.3 enabled, so old clients fail; or obsolete TLSv1.0 left on.
5. Proxying to an HTTPS upstream without proxy_ssl_server_name, so SNI-based upstreams fail.
#### Diagnosis commands
- `openssl s_client -connect example.com:443 -servername example.com </dev/null | head -20` — Inspect chain and negotiation
- `openssl x509 -noout -modulus -in fullchain.pem | md5sum; openssl rsa -noout -modulus -in privkey.pem | md5sum` — Hashes must match (RSA keys)
- `openssl x509 -noout -dates -in /etc/letsencrypt/live/example.com/fullchain.pem` — Validity dates
#### Fix configs
Proxy to an HTTPS upstream:
```nginx
location / {
    proxy_pass https://upstream.example.net;
    proxy_ssl_server_name on;
    proxy_ssl_name upstream.example.net;
    proxy_set_header Host upstream.example.net;
}
```
#### Key facts and sources
- ssl_certificate should point at the full chain file, server certificate first, then intermediates. Source: https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate
- Since nginx 1.23.4 the ssl_protocols default is TLSv1.2 TLSv1.3. Source: https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_protocols
#### FAQ
- **Browsers work but curl or an app fails?** Usually a missing intermediate. Browsers fetch it themselves; curl and many apps do not. Use fullchain.pem.
- **Where can I see the certificate expiry?** Run openssl x509 -noout -dates, or check online at ssl.sh. nginx.cc/fix also flags certs expiring within 14 days.

### nginx: bind() failed (98: Address already in use)
Page: https://nginx.cc/en/errors/address-already-in-use · Last verified: 2026-11-14

**Short answer:** Port 80/443 is already taken (Apache, Caddy, a panel, a Docker container, another nginx), or the config listens on the same IPv6 socket twice.
**Most common cause:** apache2/httpd started at boot and holds port 80.
**Try this first:** Stop and disable the other service
```nginx
systemctl disable --now apache2      # httpd on RHEL
systemctl restart nginx
```

#### Typical log lines
```
bind() to 0.0.0.0:80 failed (98: Address already in use)
bind() to [::]:443 failed (98: Address already in use)
still could not bind()
```
#### Common causes
1. apache2/httpd started at boot and holds port 80.
2. A Docker container publishes -p 80:80 or -p 443:443.
3. An old nginx master is still running (started by hand, then via systemctl).
4. Several servers repeat listen [::]:80 with conflicting ipv6only options.
#### Diagnosis commands
- `ss -ltnp '( sport = :80 or sport = :443 )'` — Who holds the ports
- `docker ps --format '{{.Names}} {{.Ports}}' | grep -E ':(80|443)->'` — Is a container publishing them
- `ps -ef | grep [n]ginx` — Leftover nginx processes
#### Fix configs
Leftover master process:
```nginx
nginx -s quit || pkill -QUIT -x nginx
systemctl start nginx
```
Set IPv6 listen options once:
```nginx
# ipv6only, default_server, reuseport and similar parameters may appear in only one server per address:port
listen 80 default_server;
listen [::]:80 default_server;
```
#### Key facts and sources
- listen's ipv6only parameter defaults to on, so listen 80 and listen [::]:80 can coexist. Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#listen
#### FAQ
- **Can nginx and Apache both use port 80?** Not on the same port. Move Apache to 8080 and let nginx on 80/443 proxy to it.
- **A Docker container holds port 80. What now?** Find the container publishing 0.0.0.0:80 with docker ps, stop it or move it to another port, and let nginx reverse-proxy to that port.

### upstream prematurely closed connection: causes and fixes
Page: https://nginx.cc/en/errors/upstream-prematurely-closed · Last verified: 2026-11-14

**Short answer:** The backend closed the connection before nginx got the full response. Typical causes: backend crash or self-timeout, mismatched keepalive, a WebSocket not upgraded properly, or backend timeouts on large downloads.
**Most common cause:** Backend crashed mid-request (OOM, uncaught exception) or PHP's max_execution_time hit.
**Try this first:** Correct upstream keepalive
```nginx
upstream app {
    server 127.0.0.1:3000;
    keepalive 32;
}
location / {
    proxy_pass http://app;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
}
```

#### Typical log lines
```
upstream prematurely closed connection while reading response header from upstream
upstream prematurely closed connection while reading upstream
```
#### Common causes
1. Backend crashed mid-request (OOM, uncaught exception) or PHP's max_execution_time hit.
2. upstream keepalive without proxy_http_version 1.1 and Connection "", or backend keepalive timeout shorter than nginx's.
3. WebSocket Upgrade/Connection headers not forwarded.
4. Gunicorn/uWSGI worker timeout (default 30 s) kills the worker.
#### Diagnosis commands
- `journalctl -u your-app -n 100 --no-pager` — Backend crash logs at the same time
- `dmesg -T | grep -i -E 'killed process|oom'` — OOM kills
- `curl -sv http://127.0.0.1:3000/path -o /dev/null` — Does the backend drop direct requests too
#### Fix configs
WebSocket:
```nginx
map $http_upgrade $connection_upgrade { default upgrade; '' close; }
location /ws/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
    proxy_read_timeout 3600s;
}
```
Gunicorn timeout:
```nginx
gunicorn app:app --timeout 120 --workers 3
```
#### Key facts and sources
- Proxying WebSocket needs HTTP/1.1 plus the Upgrade / Connection headers; proxy_http_version defaults to 1.1 since nginx 1.29.7, older versions must set it. Source: https://nginx.org/en/docs/http/websocket.html
- HTTP upstream keepalive needs proxy_http_version 1.1 (the default since 1.29.7) or 2 and a cleared Connection header; the official example marks both lines as needed only before 1.29.7. Source: https://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive
#### FAQ
- **Is this an nginx bug?** Almost never. It means the backend hung up first; look in the backend logs.
- **Do users see a 502 or a broken download?** If the backend drops before the response headers, nginx returns 502; if it drops after they were sent, users get a truncated page or a broken download.

### nginx (13: Permission denied): troubleshooting
Page: https://nginx.cc/en/errors/permission-denied · Last verified: 2026-11-14

**Short answer:** 13: Permission denied appears when reading files, connecting to a socket, writing logs or binding ports: the worker user lacks rights, a parent dir is not traversable, the socket owner is wrong, or SELinux blocks it.
**Most common cause:** Site under /home/user or /root without execute permission on parents.
**Try this first:** Make parents traversable
```nginx
chmod o+x /home/deploy /home/deploy/site
# better: keep sites under /var/www, owned by the deploy user, group www-data
```

#### Typical log lines
```
open() "/home/deploy/site/index.html" failed (13: Permission denied)
connect() to unix:/run/php/php8.3-fpm.sock failed (13: Permission denied) while connecting to upstream
bind() to 0.0.0.0:80 failed (13: Permission denied)
open() "/var/log/nginx/access.log" failed (13: Permission denied)
```
#### Common causes
1. Site under /home/user or /root without execute permission on parents.
2. PHP-FPM socket listen.owner/listen.group is not the nginx user.
3. Running nginx as non-root while binding ports below 1024.
4. SELinux blocks reading non-standard dirs or connecting to sockets.
#### Diagnosis commands
- `ps -o user= -C nginx | sort | uniq -c` — Which user the workers run as
- `namei -l /home/deploy/site/index.html` — Permissions per path component
- `ls -l /run/php/*.sock` — Socket owner
- `ausearch -m avc -ts recent | tail` — SELinux denials
#### Fix configs
PHP-FPM socket owner:
```nginx
; /etc/php/8.3/fpm/pool.d/www.conf
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
; on RHEL use nginx, then restart php-fpm
```
SELinux:
```nginx
semanage fcontext -a -t httpd_sys_content_t '/srv/site(/.*)?'
restorecon -Rv /srv/site
setsebool -P httpd_can_network_connect 1   # when nginx must connect to backend ports
```
#### Key facts and sources
- Workers run with the user and group named by the user directive (default nobody nobody), so check that line at the top of nginx.conf. Source: https://nginx.org/en/docs/ngx_core_module.html#user
#### FAQ
- **Can I just set user root?** No. Root workers turn any bug into full host compromise. Fix file and socket permissions instead.
- **Will chmod -R 777 fix it?** Don't. 777 lets any user modify your files. Give the nginx user x on every directory in the path and r on the files (typically 755 / 644) and check each level with namei -l.

### Nginx 400 Request Header Or Cookie Too Large: fix
Page: https://nginx.cc/en/errors/400-request-header-too-large · Last verified: 2026-11-14

**Short answer:** 400 “Request Header Or Cookie Too Large” means one request header line, usually Cookie, is larger than a single large_client_header_buffers buffer (8k by default). Clear the site's cookies to confirm, then raise it to 16k or 32k in http {}.
**Most common cause:** Cookies pile up: analytics, A/B testing and ad scripts each add some, or the app stores a whole session / JWT in a cookie.
**Try this first:** Raise the header buffers at http level
```nginx
http {
    large_client_header_buffers 4 32k;   # default 4 8k
}
```

#### Typical log lines
```
client sent too long header line: "Cookie: …" while reading client request headers
client sent too long URI while reading client request line
```
#### Common causes
1. Cookies pile up: analytics, A/B testing and ad scripts each add some, or the app stores a whole session / JWT in a cookie.
2. Single sign-on sends a very long Authorization header.
3. A very long query string gives 414 Request-URI Too Large instead; the same directive controls it.
4. Raised only in a non-default server: header parsing can start before the server is chosen, so the default server's value may apply.
#### Diagnosis commands
- `grep 'too long header line' /var/log/nginx/error.log | tail -3` — Logged at info level; invisible if error_log is set above info
- `curl -s -o /dev/null -w '%{http_code}\n' -H "Cookie: big=$(head -c 12000 /dev/zero | tr '\0' x)" https://example.com/` — Reproduce with a 12 KB cookie
- `nginx -T 2>/dev/null | grep -n large_client_header_buffers` — Current value and where it is set
#### Fix configs
App side: keep big data out of cookies:
```nginx
# keep session data server-side (Redis / database); the cookie only holds the session ID
# drop unused analytics and A/B-testing cookies
```
#### Key facts and sources
- large_client_header_buffers defaults to 4 8k: a header line larger than one buffer returns 400, an oversized request line returns 414. Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#large_client_header_buffers
- When set at server level, the default server's value can be used. Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#large_client_header_buffers
#### FAQ
- **Why do only some users see it?** Only browsers that accumulated many cookies exceed 8k; a private window usually works, which confirms it is the cookies.
- **How large should it be?** 16k or 32k covers almost every site. Going higher only hides an app that stores too much in cookies and costs memory per connection.

### Nginx 499 Client Closed Request: what it means
Page: https://nginx.cc/en/errors/499-client-closed-request · Last verified: 2026-11-14

**Short answer:** 499 is an nginx-specific code that only appears in access logs: the client closed the connection before nginx answered. Many 499s usually mean a slow backend and a CDN or load balancer in front that gave up first. Find the slow requests, then align timeouts across layers.
**Most common cause:** The backend is slow and the user reloaded or closed the page.
**Try this first:** Log timings to find slow requests
```nginx
log_format timed '$remote_addr [$time_local] "$request" $status '
                 'rt=$request_time urt=$upstream_response_time';
access_log /var/log/nginx/timed.log timed;
```

#### Typical log lines
```
203.0.113.7 - - [14/Nov/2026:10:00:00 +0800] "POST /api/export HTTP/1.1" 499 0 "-" "Mozilla/5.0"
epoll_wait() reported that client prematurely closed connection, so upstream connection is closed too while sending request to upstream
```
#### Common causes
1. The backend is slow and the user reloaded or closed the page.
2. A CDN, load balancer or API gateway in front has a shorter timeout than the backend needs and drops its connection to nginx.
3. Health checks or monitors use very short timeouts.
4. Client code cancels requests on purpose (front-end aborts on navigation).
#### Diagnosis commands
- `awk '$9==499' /var/log/nginx/access.log | awk '{print $7}' | sort | uniq -c | sort -rn | head` — Which paths get most 499s (default combined log format)
- `awk '$9==499' /var/log/nginx/access.log | wc -l` — How many 499s, compared with a normal day
- `time curl -s -o /dev/null http://127.0.0.1:3000/api/export` — Time the backend directly
#### Fix configs
Let long jobs finish on the backend (optional):
```nginx
location /api/export {
    proxy_ignore_client_abort on;   # keep waiting for the backend after the client disconnects
    proxy_read_timeout 300s;
    proxy_pass http://127.0.0.1:3000;
}
```
#### Key facts and sources
- proxy_ignore_client_abort defaults to off: when the client disconnects, nginx also closes the upstream connection. Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ignore_client_abort
- $request_time counts from the first byte read from the client, in seconds with millisecond resolution. Source: https://nginx.org/en/docs/http/ngx_http_log_module.html#var_request_time
#### FAQ
- **Is 499 an error I must fix?** A few 499s are normal (users leave). Many on a few endpoints, or clustered around a CDN timeout, mean the backend is too slow.
- **Why don't browsers show 499?** The connection is already gone, so 499 is never sent; it is only written to nginx's access log.

### Nginx 500: rewrite or internal redirection cycle
Page: https://nginx.cc/en/errors/500-rewrite-cycle · Last verified: 2026-11-14

**Short answer:** “rewrite or internal redirection cycle” means the request was redirected internally more than 10 times and nginx gave up with 500. Most often the try_files fallback (say /index.html) does not exist and lands in the same location again. Check root and the entry file, then end the chain with =404.
**Most common cause:** try_files falls back to /index.html or /index.php but root points at the wrong directory, so the entry file is missing.
**Try this first:** End the fallback chain with =404
```nginx
location / {
    root /var/www/site/dist;   # make sure index.html really is here
    try_files $uri $uri/ /index.html =404;
}
```

#### Typical log lines
```
rewrite or internal redirection cycle while internally redirecting to "/index.html"
rewrite or internal redirection cycle while processing "/index.php"
```
#### Common causes
1. try_files falls back to /index.html or /index.php but root points at the wrong directory, so the entry file is missing.
2. A rewrite without last / break produces a URI that matches the same rule again.
3. error_page points at a page that fails the same way.
4. The front-end build was never uploaded (empty dist directory).
#### Diagnosis commands
- `grep 'redirection cycle' /var/log/nginx/error.log | tail -3` — Which URI it loops on
- `nginx -T 2>/dev/null | grep -nE 'root|try_files|rewrite|error_page'` — The directives involved
- `ls -l /var/www/site/index.html` — Does the fallback target exist
#### Fix configs
Give rewrites last or break:
```nginx
location /blog/ {
    rewrite ^/blog/(.*)$ /index.php?p=$1 last;
}
```
#### Key facts and sources
- try_files checks only the parameters before the last one; the last one triggers an internal redirect or is =code. Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#try_files
- rewrite's last searches locations again with the new URI; break continues inside the current location. Source: https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite
#### FAQ
- **Why 500 and not 404?** nginx treats more than 10 internal redirects as a configuration error and returns 500. Once the path is fixed you get 200 or 404 as normal.
- **My SPA returns 500 on reload. Why?** Usually root does not point at the build directory (dist / build), so /index.html is missing. Fix root.

### nginx + PHP-FPM “File not found” / Primary script unknown
Page: https://nginx.cc/en/errors/php-fpm-primary-script-unknown · Last verified: 2026-11-14

**Short answer:** A bare “File not found.” page with “Primary script unknown” in the log means PHP-FPM could not open the file named by SCRIPT_FILENAME. Nine times out of ten SCRIPT_FILENAME is missing or $document_root is wrong (root set inside a location); otherwise PHP-FPM cannot read the file or open_basedir blocks it.
**Most common cause:** SCRIPT_FILENAME is not set: include fastcgi_params alone is not enough (Debian's fastcgi.conf / snippets/fastcgi-php.conf sets it).
**Try this first:** root at server level, explicit SCRIPT_FILENAME
```nginx
server {
    root /var/www/site;   # at server level so every location inherits it
    index index.php index.html;

    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }
}
```

#### Typical log lines
```
FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream
FastCGI sent in stderr: "PHP message: PHP Warning:  Unknown: open_basedir restriction in effect."
```
#### Common causes
1. SCRIPT_FILENAME is not set: include fastcgi_params alone is not enough (Debian's fastcgi.conf / snippets/fastcgi-php.conf sets it).
2. root is set only inside location /, so the PHP location does not inherit it and $document_root falls back to the default html directory.
3. The PHP-FPM pool user (e.g. www-data) cannot read the site directory.
4. PHP-FPM runs in a container where the path differs from what nginx sees.
5. open_basedir in php.ini or the pool config does not include the site directory.
#### Diagnosis commands
- `grep -E 'Primary script unknown|open_basedir' /var/log/nginx/error.log | tail -3` — Which one it is
- `nginx -T 2>/dev/null | grep -nE 'root|SCRIPT_FILENAME|fastcgi_pass|include'` — Where SCRIPT_FILENAME and root are
- `sudo -u www-data test -r /var/www/site/index.php && echo readable` — Can the PHP-FPM user read the file
#### Fix configs
PHP-FPM in a container: use its own path:
```nginx
fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name;   # the site directory inside the container
fastcgi_pass php:9000;
```
#### Key facts and sources
- $fastcgi_script_name is the request URI (plus fastcgi_index when the URI ends with a slash). Source: https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#var_fastcgi_script_name
- fastcgi_param directives are inherited from the previous level only if none are defined at the current level. Source: https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_param
#### FAQ
- **fastcgi_params vs fastcgi.conf?** fastcgi.conf is fastcgi_params plus a SCRIPT_FILENAME line. With fastcgi_params you must set SCRIPT_FILENAME yourself.
- **Why do only PHP files fail?** nginx serves static files via root; PHP-FPM opens PHP files via SCRIPT_FILENAME, so a path or permission mismatch breaks only PHP.

### Nginx 502: upstream sent too big header
Page: https://nginx.cc/en/errors/upstream-sent-too-big-header · Last verified: 2026-11-14

**Short answer:** “upstream sent too big header” means the backend's response headers (usually many or large Set-Cookie headers, or a long Location) exceed proxy_buffer_size / fastcgi_buffer_size (one memory page, 4k or 8k, by default), so nginx returns 502. Raise the matching buffer size to 16k–32k and check why the app sends such headers.
**Most common cause:** Login or SSO callbacks set several large cookies at once.
**Try this first:** Reverse proxy (proxy_pass)
```nginx
proxy_buffer_size 16k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 32k;
```

#### Typical log lines
```
upstream sent too big header while reading response header from upstream
upstream sent too big header while reading response header from upstream, client: 203.0.113.7, server: example.com, request: "POST /login HTTP/1.1", upstream: "fastcgi://unix:/run/php/php8.3-fpm.sock:"
```
#### Common causes
1. Login or SSO callbacks set several large cookies at once.
2. The app puts debug data or permission lists into headers.
3. WordPress plugins or Magento admin pages send long Link / Set-Cookie headers.
#### Diagnosis commands
- `grep 'too big header' /var/log/nginx/error.log | tail -3` — The upstream field shows proxy or fastcgi
- `curl -s -D - -o /dev/null http://127.0.0.1:3000/login | wc -c` — Measure header size bypassing nginx
#### Fix configs
PHP-FPM (fastcgi_pass):
```nginx
fastcgi_buffer_size 32k;
fastcgi_buffers 16 16k;
fastcgi_busy_buffers_size 32k;
```
#### Key facts and sources
- proxy_buffer_size is used for the first part of the response (the headers) and defaults to one memory page: 4k or 8k. Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffer_size
- fastcgi_buffer_size plays the same role for FastCGI, also 4k or 8k by default. Source: https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_buffer_size
#### FAQ
- **Any downside to bigger buffers?** A bit more memory per connection. 16k–32k is harmless for most sites; needing hundreds of KB means the app should change.
- **Why change busy_buffers_size too?** proxy_busy_buffers_size must be at least the larger of proxy_buffer_size and one proxy_buffers buffer, or nginx -t fails.

### nginx: no resolver defined to resolve — causes and fix
Page: https://nginx.cc/en/errors/no-resolver-defined · Last verified: 2026-11-14

**Short answer:** When proxy_pass contains a variable (proxy_pass https://$host, $backend…), the name is resolved per request, and nginx does not read /etc/resolv.conf: you must name DNS servers with resolver. Without it nginx logs “no resolver defined” and returns 502. Add resolver, or use an upstream / a variable-free proxy_pass.
**Most common cause:** proxy_pass contains a variable and no resolver is configured.
**Try this first:** Set a resolver
```nginx
http {
    resolver 1.1.1.1 8.8.8.8 valid=300s ipv6=off;
    resolver_timeout 5s;
}
```

#### Typical log lines
```
no resolver defined to resolve api.example.com, client: 203.0.113.7
api.example.com could not be resolved (3: Host not found)
```
#### Common causes
1. proxy_pass contains a variable and no resolver is configured.
2. Proxying to a Docker service name needs Docker's embedded DNS at 127.0.0.11.
3. resolver points at 127.0.0.53 (systemd-resolved), which does not exist inside a container.
#### Diagnosis commands
- `grep -E 'no resolver|could not be resolved' /var/log/nginx/error.log | tail -3` — Confirm the error
- `nginx -T 2>/dev/null | grep -nE 'resolver|proxy_pass .*\$'` — Which proxy_pass lines use variables
- `grep nameserver /etc/resolv.conf` — The system DNS (nginx does not read it)
#### Fix configs
Inside Docker:
```nginx
resolver 127.0.0.11 valid=30s;   # Docker's embedded DNS
set $backend http://app:3000;
proxy_pass $backend;
```
No dynamic resolution needed: drop the variable:
```nginx
upstream api {
    server api.example.com:443;
}
proxy_pass https://api;   # resolved once at startup
```
#### Key facts and sources
- When the proxy_pass address contains variables, the name is resolved at run time and needs a resolver (unless it matches a defined upstream). Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass
- resolver caches answers for their TTL by default; the valid parameter overrides it. Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#resolver
#### FAQ
- **Why is no resolver needed without variables?** Without variables nginx resolves the name at startup and reload with the system resolver; the catch is that IP changes need a reload.
- **What does valid=300s do?** It overrides the record's TTL and caches answers for 300 seconds.

### could not build server_names_hash: how to fix
Page: https://nginx.cc/en/errors/server-names-hash-bucket-size · Last verified: 2026-11-14

**Short answer:** nginx -t failing with “could not build server_names_hash, you should increase server_names_hash_bucket_size” means a server_name is too long (or there are too many names) for the default hash bucket. Set server_names_hash_bucket_size 64 (then 128) in http {}, and raise server_names_hash_max_size for very many names.
**Most common cause:** Very long names (deep subdomains, long random prefixes).
**Try this first:** Raise it at http level
```nginx
http {
    server_names_hash_bucket_size 64;   # use 128 if 64 is not enough
    server_names_hash_max_size 1024;    # for many names
}
```

#### Typical log lines
```
nginx: [emerg] could not build server_names_hash, you should increase server_names_hash_bucket_size: 32
nginx: [warn] could not build optimal server_names_hash, you should increase either server_names_hash_max_size: 512 or server_names_hash_bucket_size: 64
```
#### Common causes
1. Very long names (deep subdomains, long random prefixes).
2. Hundreds or thousands of server_name entries on one host.
3. The default bucket size depends on the CPU cache line (32, 64 or 128), so a config can start failing on another machine.
#### Diagnosis commands
- `nginx -t` — emerg (must fix) or warn (should fix)
- `nginx -T 2>/dev/null | grep -o 'server_name[^;]*' | awk '{for(i=2;i<=NF;i++) print length($i), $i}' | sort -rn | head` — The longest names
#### Fix configs
#### Key facts and sources
- server_names_hash_bucket_size defaults to 32|64|128, depending on the processor's cache line size. Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#server_names_hash_bucket_size
- server_names_hash_max_size defaults to 512. Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#server_names_hash_max_size
- Official guidance: with many names, first set server_names_hash_max_size close to the number of names; for the bucket_size error, use the next power of two (e.g. 32 → 64). Source: https://nginx.org/en/docs/http/server_names.html#optimization
#### FAQ
- **Can it go inside server?** No. Both are http-level only; inside server nginx -t reports “directive is not allowed here”.
- **Do I need to act on the warn?** The warn does not block startup; lookups are just less efficient. Raise one of the two values to silence it.

### nginx warning: conflicting server name … ignored
Page: https://nginx.cc/en/errors/conflicting-server-name · Last verified: 2026-11-14

**Short answer:** “conflicting server name "example.com" on 0.0.0.0:80, ignored” means two server blocks on the same address and port declare the same name; the one read later is ignored, so your edits may not apply at all. Use nginx -T to find the duplicate and remove the extra file (often default, a .bak copy, or a duplicate symlink in sites-enabled).
**Most common cause:** Backup files (example.conf.bak, example.conf~) left in sites-enabled are picked up when the include is not limited to *.conf.
**Try this first:** Remove the duplicate site file
```nginx
rm /etc/nginx/sites-enabled/example.conf.bak
nginx -t && systemctl reload nginx
```

#### Typical log lines
```
nginx: [warn] conflicting server name "example.com" on 0.0.0.0:80, ignored
nginx: [warn] conflicting server name "example.com" on [::]:443, ignored
```
#### Common causes
1. Backup files (example.conf.bak, example.conf~) left in sites-enabled are picked up when the include is not limited to *.conf.
2. The same site exists in both conf.d and sites-enabled.
3. certbot --nginx rewrote the file and a second server with the same name was added by hand.
#### Diagnosis commands
- `nginx -T 2>/dev/null | grep -nE '^# configuration file|server_name'` — Which file each server_name comes from
- `ls -la /etc/nginx/sites-enabled/ /etc/nginx/conf.d/` — Look for backups and duplicate links
#### Fix configs
Include only .conf files:
```nginx
# rename site files to end in .conf first (Debian's default has no extension)
http {
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*.conf;
}
```
#### Key facts and sources
- nginx picks a server by listen address and port first, then by server_name; with no match on that port it uses the default_server. Source: https://nginx.org/en/docs/http/request_processing.html
- nginx -T tests the configuration and dumps every loaded file. Source: https://nginx.org/en/docs/switches.html
#### FAQ
- **It is only a warning. Can I ignore it?** Better not. The ignored server may be the one you just edited, which looks like “my changes do nothing”.
- **Is one server on 80 and one on 443 a conflict?** No. The conflict is the same name on the same address and port.

### Nginx 405 Not Allowed: why POST is rejected
Page: https://nginx.cc/en/errors/405-not-allowed · Last verified: 2026-11-14

**Short answer:** nginx answering 405 Not Allowed usually means a POST (or PUT, DELETE) request ended up on a static file, which only accepts GET and HEAD. Typically the API path was not handed to proxy_pass / fastcgi_pass and try_files fell back to index.html. Route the API location to the backend.
**Most common cause:** An SPA's try_files $uri /index.html also sends POST /api/... to index.html.
**Try this first:** Send the API to the backend
```nginx
location /api/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
}
location / {
    try_files $uri $uri/ /index.html;
}
```

#### Typical log lines
```
"POST /api/login HTTP/1.1" 405 157
405 Not Allowed
```
#### Common causes
1. An SPA's try_files $uri /index.html also sends POST /api/... to index.html.
2. The API location prefix is wrong (/api vs /api/), so requests miss proxy_pass.
3. A form posts to a static .html page.
4. A limit_except GET method restriction is in place.
#### Diagnosis commands
- `curl -si -X POST https://example.com/api/login | head -5` — Is the 405 from nginx or from the backend
- `nginx -T 2>/dev/null | grep -nE 'location|try_files|proxy_pass|limit_except'` — Which location the request matches
#### Fix configs
#### Key facts and sources
- limit_except restricts the HTTP methods allowed in a location; allowing GET also allows HEAD. Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#limit_except
- error_page with a URI does an internal redirect and changes methods other than GET and HEAD to GET; pointing it at a named location (error_page 405 = @name) keeps the URI and method. Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#error_page
#### FAQ
- **Can I work around it with error_page 405 =200 $uri?** It makes the page render, but the POST body is thrown away and nothing handles it. Send the request to the backend that should process it.
- **How do I tell nginx's 405 from the app's?** nginx's 405 page has an nginx footer and Server: nginx; an app's 405 usually carries an Allow header and its own error format.

### nginx unknown directive: http2, brotli, quic and more
Page: https://nginx.cc/en/errors/unknown-directive · Last verified: 2026-11-14

**Short answer:** nginx -t reporting “unknown directive "http2"” and the like means this nginx does not know the directive: the version is too old (http2 on needs 1.25.1+), the module is not built in or not loaded (brotli and headers-more are third-party), or it is a typo or an invisible character. Check nginx -V, then change the syntax or install the module.
**Most common cause:** The distro nginx is too old: Debian 12 ships 1.22, Ubuntu 24.04 ships 1.24, neither has http2 on;.
**Try this first:** HTTP/2 on older versions
```nginx
# nginx < 1.25.1
listen 443 ssl http2;
# nginx ≥ 1.25.1
listen 443 ssl;
http2 on;
```

#### Typical log lines
```
nginx: [emerg] unknown directive "http2" in /etc/nginx/sites-enabled/example.conf:4
nginx: [emerg] unknown directive "brotli" in /etc/nginx/nginx.conf:30
nginx: [emerg] unknown directive "more_set_headers" in /etc/nginx/conf.d/security.conf:2
```
#### Common causes
1. The distro nginx is too old: Debian 12 ships 1.22, Ubuntu 24.04 ships 1.24, neither has http2 on;.
2. Third-party modules (brotli, more_set_headers) are not installed or load_module is missing.
3. listen … quic needs nginx 1.25.0+ built with --with-http_v3_module.
4. Config copied from a web page carries full-width spaces, zero-width characters or CJK punctuation.
#### Diagnosis commands
- `nginx -V 2>&1 | tr ' ' '\n' | grep -E 'version|http_v2|http_v3|brotli|headers-more'` — Version and built-in modules
- `ls /etc/nginx/modules-enabled/ /usr/lib/nginx/modules/ 2>/dev/null` — Loadable dynamic modules
- `grep -nP '[^\x00-\x7F]' /etc/nginx/sites-enabled/example.conf` — Find non-ASCII characters
#### Fix configs
Install the brotli module on Debian 12+:
```nginx
apt install libnginx-mod-http-brotli-filter libnginx-mod-http-brotli-static
nginx -t && systemctl reload nginx
```
Or switch to a current nginx.org build:
```nginx
curl -fsSL nginx.cc/install | sudo bash -s -- --dry-run
```
#### Key facts and sources
- The http2 directive appeared in nginx 1.25.1. Source: https://nginx.org/en/docs/http/ngx_http_v2_module.html#http2
- The HTTP/3 module is available since 1.25.0 and is not built by default; it needs --with-http_v3_module. Source: https://nginx.org/en/docs/http/ngx_http_v3_module.html
#### FAQ
- **Is “directive is not allowed here” the same thing?** No. It means the directive exists but sits in the wrong block (e.g. server_names_hash_bucket_size inside server); check the Context line in the docs.
- **Do nginx.org packages include brotli?** brotli is not an nginx module; it needs a third-party module package or a custom build. Debian ships libnginx-mod-http-brotli-filter since Debian 12.

### nginx cannot load certificate: missing file or key mismatch
Page: https://nginx.cc/en/errors/cannot-load-certificate · Last verified: 2026-11-14

**Short answer:** nginx -t reporting “cannot load certificate … No such file or directory” most often means ssl_certificate was written before the certificate existed (chicken and egg); “key values mismatch” means the certificate and key are not a pair. For a new site issue the certificate with an HTTP-only config first, then switch to HTTPS; for a mismatch compare the public keys with openssl.
**Most common cause:** A new site used the full HTTPS config before the certificate was issued.
**Try this first:** Issue over HTTP first, then switch to HTTPS
```nginx
server {
    listen 80;
    server_name example.com;
    location /.well-known/acme-challenge/ { root /var/www/_letsencrypt; }
}
# certbot certonly --webroot -w /var/www/_letsencrypt -d example.com
# once issued, add listen 443 ssl and ssl_certificate
```

#### Typical log lines
```
nginx: [emerg] cannot load certificate "/etc/letsencrypt/live/example.com/fullchain.pem": BIO_new_file() failed (SSL: error:80000002:system library::No such file or directory…)
nginx: [emerg] SSL_CTX_use_PrivateKey("/etc/ssl/private/example.key") failed (SSL: error:05800074:x509 certificate routines::key values mismatch)
```
#### Common causes
1. A new site used the full HTTPS config before the certificate was issued.
2. Wrong path: the live/ directory got a -0001 suffix (certbot creates a new one when issuing again).
3. The certificate was renewed but the old key is still configured, or another domain's key was used.
4. nginx cannot read the key file (mode 600 with the wrong owner).
#### Diagnosis commands
- `ls -l /etc/letsencrypt/live/` — The real certificate directory names
- `certbot certificates` — Certificates and paths certbot manages
- `openssl x509 -noout -pubkey -in fullchain.pem | sha256sum; openssl pkey -pubout -in privkey.pem | sha256sum` — The hashes must match
#### Fix configs
Reference the certificate and key as a pair:
```nginx
ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
```
#### Key facts and sources
- ssl_certificate names a PEM certificate; intermediates belong in the same file after the server certificate. Source: https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate
- Certbot's webroot plugin writes challenge files to <webroot>/.well-known/acme-challenge/. Source: https://eff-certbot.readthedocs.io/en/stable/using.html#webroot
#### FAQ
- **Why does certbot --nginx fail as well?** certbot needs nginx running, and nginx cannot start without the certificate. Comment out the 443 server or use the stage-1 config first.
- **cert.pem or fullchain.pem?** fullchain.pem. cert.pem lacks the intermediate, so some clients reject it.

## 报错百科（中文）

### Nginx 502 Bad Gateway 原因与解决方法
页面: https://nginx.cc/zh/errors/502-bad-gateway · 最后核对: 2026-11-14

**快速答案:** 502 表示 Nginx 连不上或读不懂后端（PHP-FPM、Node、Docker 容器等）。按「后端是否在跑 → 地址端口是否一致 → 权限/SELinux → 响应头过大」的顺序排查。
**最常见原因:** 后端服务没启动、崩溃或被 OOM 杀掉。
**先这样改:** 地址与后端监听保持一致
```nginx
location / {
    proxy_pass http://127.0.0.1:3000;   # 不要写 localhost
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
```

#### 典型日志
```
connect() failed (111: Connection refused) while connecting to upstream
connect() to unix:/run/php/php8.3-fpm.sock failed (2: No such file or directory)
upstream sent too big header while reading response header from upstream
no live upstreams while connecting to upstream
```
#### 常见原因
1. 后端服务没启动、崩溃或被 OOM 杀掉。
2. proxy_pass / fastcgi_pass 的地址、端口或 socket 路径写错（PHP 升级后 socket 名会变）。
3. 后端只监听 127.0.0.1，而 proxy_pass 写的是 localhost 被解析成 ::1；或 Docker 容器只监听容器内地址。
4. SELinux 禁止 nginx 发起网络连接（CentOS/Rocky/Alma 常见）。
5. 后端返回的响应头太大（大 Cookie、JWT），超出 proxy_buffer_size。
#### 排查命令
- `tail -n 50 /var/log/nginx/error.log` — 看具体是哪种 connect() 失败
- `ss -ltnp | grep -E ':3000|php-fpm'` — 确认后端确实在监听
- `curl -sv http://127.0.0.1:3000/ -o /dev/null` — 绕过 nginx 直接访问后端
- `ls -l /run/php/` — PHP-FPM socket 的真实文件名
- `systemctl status php8.3-fpm --no-pager` — 后端服务状态
- `getenforce && getsebool httpd_can_network_connect` — SELinux 是否拦截
#### 修复配置
PHP-FPM socket 路径:
```nginx
location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/run/php/php8.3-fpm.sock;   # 与 ls /run/php/ 一致
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
```
响应头过大:
```nginx
proxy_buffer_size 16k;
proxy_buffers 8 16k;
# PHP-FPM:
fastcgi_buffer_size 32k;
fastcgi_buffers 16 16k;
```
SELinux 放行（RHEL 系）:
```nginx
setsebool -P httpd_can_network_connect 1
```
#### 关键事实与出处
- proxy_buffer_size 默认是一个内存页（4k 或 8k），装不下的响应头会导致 “upstream sent too big header”。 Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffer_size
- proxy_connect_timeout 默认 60 秒，且通常不能超过 75 秒。 Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_connect_timeout
- fastcgi_pass 可以写 TCP 地址，也可以写 unix: 开头的 socket 路径。 Source: https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_pass
#### 常见问题
- **502 和 504 有什么区别？** 502 是连不上或后端回了无效响应，通常立刻出现；504 是连上了但后端在超时时间内没有回应，通常等几十秒才出现。
- **重启 nginx 能解决 502 吗？** 一般不能。502 几乎都是后端的问题，应该先看 error.log 里的 connect() 报错，再重启或修复后端。
- **用了 Cloudflare 后出现 502 怎么办？** 先看错误页是 Cloudflare 的还是 nginx 的。Cloudflare 样式的 502 表示 Cloudflare 连不上你的源站（防火墙、端口）；nginx 样式的才是本页说的后端问题。

### Nginx 504 Gateway Timeout 原因与解决方法
页面: https://nginx.cc/zh/errors/504-gateway-timeout · 最后核对: 2026-11-14

**快速答案:** 504 表示后端在 Nginx 的等待时间内没有返回。先找出慢在哪里（慢查询、外部接口、队列），再按需调大 proxy_read_timeout 或 fastcgi_read_timeout。
**最常见原因:** 后端处理太慢：慢 SQL、调用外部接口卡住、导出/上传等长任务。
**先这样改:** 只给慢接口加长超时
```nginx
location /api/export {
    proxy_pass http://127.0.0.1:3000;
    proxy_connect_timeout 5s;
    proxy_read_timeout 300s;
    proxy_send_timeout 300s;
}
```

#### 典型日志
```
upstream timed out (110: Connection timed out) while reading response header from upstream
upstream timed out (110: Connection timed out) while connecting to upstream
```
#### 常见原因
1. 后端处理太慢：慢 SQL、调用外部接口卡住、导出/上传等长任务。
2. PHP-FPM 进程池耗尽（pm.max_children 太小），请求在排队。
3. proxy_read_timeout / fastcgi_read_timeout 太短（默认 60s）。
4. 后端所在机器到上游的网络不通，连接阶段就超时。
#### 排查命令
- `grep 'upstream timed out' /var/log/nginx/error.log | tail` — 看是 connecting 还是 reading 阶段超时
- `time curl -s -o /dev/null http://127.0.0.1:3000/slow-path` — 直接测后端耗时
- `grep -i 'max_children' /var/log/php*-fpm.log` — PHP-FPM 是否到达进程上限
#### 修复配置
PHP-FPM:
```nginx
location ~ \.php$ {
    fastcgi_read_timeout 300s;
    ...
}
# 同时调整 php.ini 的 max_execution_time 和 FPM 的 pm.max_children
```
#### 关键事实与出处
- proxy_read_timeout 默认 60 秒，计的是两次读操作之间的间隔，不是整个响应的总时长。 Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_read_timeout
- fastcgi_read_timeout 默认同样是 60 秒。 Source: https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_read_timeout
#### 常见问题
- **把超时调到很大可以吗？** 可以止血但不治本。长时间占用连接会拖垮 worker 和后端，长任务更适合改成异步队列加轮询。
- **Cloudflare 的 524 和 504 一样吗？** 类似。524 是 Cloudflare 等你源站超过 100 秒（免费版）没回应，调大 nginx 超时也没用，需要让请求在 100 秒内返回。

### Nginx 413 Request Entity Too Large 上传文件太大
页面: https://nginx.cc/zh/errors/413-request-entity-too-large · 最后核对: 2026-11-14

**快速答案:** 413 是请求体超过了 client_max_body_size（默认只有 1MB）。在 http、server 或 location 中调大即可，PHP 站点还要同步改 upload_max_filesize 和 post_max_size。
**最常见原因:** 没有设置 client_max_body_size，默认 1m。
**先这样改:** 调大上传上限
```nginx
server {
    client_max_body_size 100m;   # 0 表示不限制（不推荐）
}
```

#### 典型日志
```
client intended to send too large body: 5242880 bytes
```
#### 常见原因
1. 没有设置 client_max_body_size，默认 1m。
2. 设置写在了别的 server/location 里，当前请求没命中。
3. PHP 的 upload_max_filesize / post_max_size 更小（这时报错来自 PHP，不一定是 413）。
4. 前面还有一层 CDN/面板反代，有自己的上传上限（Cloudflare 免费版 100MB）。
#### 排查命令
- `nginx -T 2>/dev/null | grep -n client_max_body_size` — 看现在生效的值和位置
- `grep 'too large body' /var/log/nginx/error.log | tail -3` — 确认是 nginx 拒绝的
- `php -i | grep -E 'upload_max_filesize|post_max_size'` — PHP 的上限
#### 修复配置
只放开上传接口:
```nginx
location /upload {
    client_max_body_size 500m;
    proxy_request_buffering off;   # 大文件边收边转
    proxy_pass http://127.0.0.1:3000;
}
```
PHP 同步修改:
```nginx
; php.ini
upload_max_filesize = 100M
post_max_size = 100M
; 然后 systemctl restart php8.3-fpm
```
#### 关键事实与出处
- client_max_body_size 默认 1m，设为 0 表示不检查请求体大小；超出时返回 413。 Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size
- PHP 默认 upload_max_filesize = 2M、post_max_size = 8M。 Source: https://www.php.net/manual/en/ini.core.php
#### 常见问题
- **改完要重启吗？** nginx -t 通过后 systemctl reload nginx 即可，不需要重启。PHP 的修改需要重启 PHP-FPM。
- **client_max_body_size 写在哪一层？** http、server、location 都可以，内层覆盖外层。建议在 server 层给一个合理值，在上传接口单独放大。

### Nginx 403 Forbidden 原因与解决方法
页面: https://nginx.cc/zh/errors/403-forbidden · 最后核对: 2026-11-14

**快速答案:** 403 通常是目录没有 index 文件、文件权限不让 nginx 读、deny 规则命中，或 SELinux 拦截。看 error.log 里是 “directory index forbidden” 还是 “Permission denied”。
**最常见原因:** 访问的是目录，但目录里没有 index 指令列出的文件，且 autoindex off。
**先这样改:** 补 index 或改成 try_files
```nginx
root /var/www/site;
index index.html index.php;
location / {
    try_files $uri $uri/ =404;   # 没有 index 时返回 404 而不是 403
}
```

#### 典型日志
```
directory index of "/var/www/site/" is forbidden
open() "/var/www/site/index.html" failed (13: Permission denied)
access forbidden by rule
```
#### 常见原因
1. 访问的是目录，但目录里没有 index 指令列出的文件，且 autoindex off。
2. nginx 运行用户（www-data / nginx）对文件或任意一级父目录没有读/执行权限。
3. 网站放在 /root 或 /home/用户 下，父目录权限 700。
4. deny all / allow 规则或 auth 命中。
5. SELinux 文件上下文不对（不是 httpd_sys_content_t）。
#### 排查命令
- `tail -n 20 /var/log/nginx/error.log` — 区分 index forbidden 和 Permission denied
- `namei -l /var/www/site/index.html` — 逐级查看每一层目录权限
- `sudo -u www-data cat /var/www/site/index.html >/dev/null && echo ok` — 以 nginx 用户身份试读（RHEL 系用 nginx）
- `ls -Z /var/www/site` — SELinux 上下文
#### 修复配置
修正权限:
```nginx
chown -R www-data:www-data /var/www/site     # RHEL 系用 nginx:nginx
find /var/www/site -type d -exec chmod 755 {} +
find /var/www/site -type f -exec chmod 644 {} +
```
SELinux 上下文:
```nginx
semanage fcontext -a -t httpd_sys_content_t '/var/www/site(/.*)?'
restorecon -Rv /var/www/site
```
#### 关键事实与出处
- index 指令按顺序查找目录的默认文件，默认值只有 index.html（PHP 站点要自己加上 index.php）。 Source: https://nginx.org/en/docs/http/ngx_http_index_module.html#index
- allow / deny 按顺序检查，第一条匹配的规则生效。 Source: https://nginx.org/en/docs/http/ngx_http_access_module.html#allow
#### 常见问题
- **chmod 777 可以解决 403 吗？** 有时能，但非常危险，任何进程都能改你的网站文件。正确做法是目录 755、文件 644，属主设为部署用户或 nginx 用户。
- **为什么放在 /root 下的网站总是 403？** /root 权限是 700，nginx 用户连目录都进不去。把网站移到 /var/www。

### Nginx 404 与 try_files：伪静态、SPA 路由、root/alias 写法
页面: https://nginx.cc/zh/errors/404-try-files · 最后核对: 2026-11-14

**快速答案:** 文件明明在却 404，多半是 root/alias 拼出来的路径不对，或 WordPress、Vue/React 路由没有用 try_files 回退到入口文件。
**最常见原因:** root 会把完整 URI 拼在后面：root /var/www/static + /static/a.js = /var/www/static/static/a.js。
**先这样改:** SPA（Vue/React）
```nginx
location / {
    try_files $uri $uri/ /index.html;
}
```

#### 典型日志
```
open() "/usr/share/nginx/html/about" failed (2: No such file or directory)
"/var/www/site/static/static/app.js" is not found (2: No such file or directory)
```
#### 常见原因
1. root 会把完整 URI 拼在后面：root /var/www/static + /static/a.js = /var/www/static/static/a.js。
2. alias 和 location 的结尾斜杠不成对。
3. SPA 前端路由（/about）刷新后服务器找不到对应文件。
4. WordPress 固定链接没有 try_files ... /index.php?$args。
5. 请求命中了另一个 server（server_name 不匹配，落到 default_server）。
#### 排查命令
- `tail -n 20 /var/log/nginx/error.log` — 看 nginx 实际去找的文件路径
- `nginx -T 2>/dev/null | grep -nE 'server_name|root|alias|try_files'` — 核对生效的 root/alias
- `curl -sI -H 'Host: example.com' http://127.0.0.1/about` — 确认命中的是哪个站
#### 修复配置
WordPress / Laravel:
```nginx
location / {
    try_files $uri $uri/ /index.php?$args;
}
```
root 与 alias 的正确写法:
```nginx
# 文件在 /var/www/static/a.js，访问 /static/a.js
location /static/ {
    alias /var/www/static/;    # 两边都带结尾斜杠
}
# 或者
location /static/ {
    root /var/www;             # root 不包含 location 前缀
}
```
#### 关键事实与出处
- try_files 按顺序检查文件是否存在，最后一个参数是回退的 URI 或 =code。 Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#try_files
- alias 会替换 location 匹配的部分，root 则把整个 URI 拼在后面。 Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#alias
#### 常见问题
- **try_files 最后一个参数有什么讲究？** 前面的参数都是「找文件」，最后一个是兜底：可以是 =404 这样的状态码，也可以是内部跳转的 URI（如 /index.html）。
- **alias 和 root 怎么选？** 目录名和 URL 前缀一致用 root，不一致用 alias。alias 一定要注意结尾斜杠，否则可能出现路径穿越。

### 重定向次数过多（ERR_TOO_MANY_REDIRECTS）的 Nginx 解决方法
页面: https://nginx.cc/zh/errors/too-many-redirects · 最后核对: 2026-11-14

**快速答案:** 浏览器提示「重定向次数过多」，最常见的是 CDN 用 HTTP 回源、源站又把 HTTP 跳到 HTTPS，形成死循环；其次是 www 和裸域互相跳、应用和 nginx 各跳一次。
**最常见原因:** Cloudflare SSL 模式为 Flexible：CDN 用 HTTP 回源，nginx 返回 301 到 HTTPS，CDN 再用 HTTP 请求……
**先这样改:** 只在 80 端口跳一次
```nginx
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://example.com$request_uri;
}
```

#### 典型日志
```
rewrite or internal redirection cycle while internally redirecting to "/index.html"
```
#### 常见原因
1. Cloudflare SSL 模式为 Flexible：CDN 用 HTTP 回源，nginx 返回 301 到 HTTPS，CDN 再用 HTTP 请求……
2. www→裸域 和 裸域→www 同时存在（nginx 一个方向、程序或 CDN 规则另一个方向）。
3. WordPress 的 siteurl 和 nginx 跳转目标不一致；反代时没有传 X-Forwarded-Proto，程序以为是 HTTP 又跳 HTTPS。
4. try_files 兜底的文件不存在，导致内部重定向循环（日志里是 internal redirection cycle）。
#### 排查命令
- `curl -sIL --max-redirs 10 http://example.com | grep -iE '^(HTTP|location)'` — 把整条跳转链打出来
- `curl -sI -H 'Host: example.com' http://127.0.0.1/` — 绕过 CDN 直接看源站跳转
- `curl -sIL --max-redirs 10 https://example.com/ | grep -iE '^(HTTP|location)'` — 看完整的跳转链在哪里绕圈
#### 修复配置
反代时告诉后端真实协议:
```nginx
proxy_set_header X-Forwarded-Proto $scheme;
# 在 Cloudflare 后面且 SSL=Full 时，$scheme 就是 https
```
Cloudflare 设置:
```nginx
# SSL/TLS → Overview → 加密模式改为 Full (strict)
# 源站需要有效证书（可用 Cloudflare Origin CA）
```
#### 关键事实与出处
- Cloudflare 的 Flexible 模式用 HTTP 回源；源站再把 HTTP 跳到 HTTPS 就会形成循环。 Source: https://developers.cloudflare.com/ssl/origin-configuration/ssl-modes/flexible/
- return 301 / 302 直接结束处理并返回跳转。 Source: https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#return
#### 常见问题
- **清浏览器缓存有用吗？** 301 会被浏览器缓存，修好后若仍循环，用无痕窗口或清缓存再试。但根因必须在服务器侧修。
- **改好了浏览器还是提示重定向过多？** 301 会被浏览器缓存，旧的跳转可能还在。用无痕窗口或 curl -I 验证，必要时清除该站点的缓存和 Cookie。

### Nginx SSL 握手失败（SSL handshake failed）排查
页面: https://nginx.cc/zh/errors/ssl-handshake-failed · 最后核对: 2026-11-14

**快速答案:** SSL 握手失败多见于：证书没用 fullchain、证书和私钥不匹配、443 没写 ssl 参数、协议/加密套件太旧或太新，以及 CDN 回源时 SNI 不匹配。
**最常见原因:** ssl_certificate 用了 cert.pem 而不是 fullchain.pem，部分客户端缺中间证书。
**先这样改:** 标准 HTTPS 配置
```nginx
server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;
    server_name example.com;
    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_session_cache shared:SSL:10m;
}
```

#### 典型日志
```
SSL_do_handshake() failed (SSL: error:0A00010B:SSL routines::wrong version number)
SSL_CTX_use_PrivateKey("/etc/ssl/private/key.pem") failed (SSL: error:05800074:x509 certificate routines::key values mismatch)
peer closed connection in SSL handshake while SSL handshaking to upstream
```
#### 常见原因
1. ssl_certificate 用了 cert.pem 而不是 fullchain.pem，部分客户端缺中间证书。
2. 证书与私钥不配对（续期后只换了一个）。
3. listen 443 没加 ssl，nginx 在 443 上讲明文 HTTP（wrong version number）。
4. 只开了 TLSv1.3，老设备/老 Java 客户端连不上；或开了已淘汰的 TLSv1.0。
5. 反代 HTTPS 上游时没开 proxy_ssl_server_name，上游按 SNI 选证书失败。
#### 排查命令
- `openssl s_client -connect example.com:443 -servername example.com </dev/null | head -20` — 看证书链和协商结果
- `openssl x509 -noout -modulus -in fullchain.pem | md5sum; openssl rsa -noout -modulus -in privkey.pem | md5sum` — 两个结果相同才配对（RSA）
- `openssl x509 -noout -dates -in /etc/letsencrypt/live/example.com/fullchain.pem` — 证书有效期
#### 修复配置
反代到 HTTPS 上游:
```nginx
location / {
    proxy_pass https://upstream.example.net;
    proxy_ssl_server_name on;
    proxy_ssl_name upstream.example.net;
    proxy_set_header Host upstream.example.net;
}
```
#### 关键事实与出处
- ssl_certificate 应指向包含中间证书的完整链文件（服务器证书在前）。 Source: https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate
- ssl_protocols 在 nginx 1.23.4 起默认是 TLSv1.2 TLSv1.3。 Source: https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_protocols
#### 常见问题
- **浏览器正常，curl 或 App 却握手失败？** 多半是缺中间证书。浏览器会自己补链，curl 和很多 App 不会。把 ssl_certificate 换成 fullchain.pem。
- **在哪查证书到期时间？** 服务器上用 openssl x509 -noout -dates，或者到 ssl.sh 在线查看。nginx.cc/fix 也会检查 14 天内过期的证书。

### Nginx 启动失败：98: Address already in use（端口被占用）
页面: https://nginx.cc/zh/errors/address-already-in-use · 最后核对: 2026-11-14

**快速答案:** 80/443 端口已经被别的程序占了（Apache、Caddy、宝塔、Docker 容器、另一个 nginx 实例），或配置里同一端口写了重复的 IPv6 监听。
**最常见原因:** apache2/httpd 随系统启动占了 80。
**先这样改:** 停掉并禁用占用者
```nginx
systemctl disable --now apache2      # RHEL 系为 httpd
systemctl restart nginx
```

#### 典型日志
```
bind() to 0.0.0.0:80 failed (98: Address already in use)
bind() to [::]:443 failed (98: Address already in use)
still could not bind()
```
#### 常见原因
1. apache2/httpd 随系统启动占了 80。
2. Docker 容器发布了 -p 80:80 或 -p 443:443。
3. 旧的 nginx 进程没退出（手动 nginx 启动后又用 systemctl 启动）。
4. 多个 server 都写了 listen [::]:80 ipv6only=off 之类的重复参数。
#### 排查命令
- `ss -ltnp '( sport = :80 or sport = :443 )'` — 看是谁占了端口
- `docker ps --format '{{.Names}} {{.Ports}}' | grep -E ':(80|443)->'` — 容器是否占用
- `ps -ef | grep [n]ginx` — 是否有残留 nginx 进程
#### 修复配置
残留进程:
```nginx
nginx -s quit || pkill -QUIT -x nginx
systemctl start nginx
```
IPv6 监听只写一次参数:
```nginx
# ipv6only、default_server、reuseport 等参数每个地址:端口只能出现在一个 server 里
listen 80 default_server;
listen [::]:80 default_server;
```
#### 关键事实与出处
- listen 的 ipv6only 参数默认 on，所以 listen 80 和 listen [::]:80 可以同时存在。 Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#listen
#### 常见问题
- **能让 nginx 和 Apache 同时用 80 吗？** 不能同时监听同一个端口。常见做法是 Apache 改到 8080，nginx 在 80/443 前面反代给它。
- **是 Docker 容器占了 80 端口怎么办？** 用 docker ps 找到映射了 0.0.0.0:80 的容器，停掉它或改成别的端口，再由 nginx 反向代理到这个端口。

### upstream prematurely closed connection 原因与解决
页面: https://nginx.cc/zh/errors/upstream-prematurely-closed · 最后核对: 2026-11-14

**快速答案:** 后端在 Nginx 还没收完响应时就把连接关了。常见于后端进程崩溃或超时自杀、keepalive 设置不一致、WebSocket 没有正确升级，以及大文件下载时后端超时。
**最常见原因:** 后端进程处理请求时崩溃（内存不足、未捕获异常），或 PHP 的 max_execution_time 到了。
**先这样改:** upstream keepalive 正确写法
```nginx
upstream app {
    server 127.0.0.1:3000;
    keepalive 32;
}
location / {
    proxy_pass http://app;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
}
```

#### 典型日志
```
upstream prematurely closed connection while reading response header from upstream
upstream prematurely closed connection while reading upstream
```
#### 常见原因
1. 后端进程处理请求时崩溃（内存不足、未捕获异常），或 PHP 的 max_execution_time 到了。
2. upstream keepalive 开着，但没有 proxy_http_version 1.1 和 Connection ""，或后端的 keepalive 超时比 nginx 短。
3. WebSocket 没有转发 Upgrade/Connection 头。
4. Gunicorn/uWSGI worker 超时（默认 30s）被杀。
#### 排查命令
- `journalctl -u your-app -n 100 --no-pager` — 后端同一时间有没有崩溃日志
- `dmesg -T | grep -i -E 'killed process|oom'` — 是否被 OOM 杀掉
- `curl -sv http://127.0.0.1:3000/path -o /dev/null` — 直接请求后端是否也被断开
#### 修复配置
WebSocket:
```nginx
map $http_upgrade $connection_upgrade { default upgrade; '' close; }
location /ws/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
    proxy_read_timeout 3600s;
}
```
Gunicorn 超时:
```nginx
gunicorn app:app --timeout 120 --workers 3
```
#### 关键事实与出处
- 代理 WebSocket 需要 HTTP/1.1 并转发 Upgrade / Connection 头；proxy_http_version 从 nginx 1.29.7 起默认就是 1.1，更早的版本要显式写上。 Source: https://nginx.org/en/docs/http/websocket.html
- HTTP 的 upstream keepalive 要求 proxy_http_version 为 1.1（1.29.7 起的默认值）或 2，并清空 Connection 头；官方示例把这两行都标注为“1.29.7 之前的版本”才需要。 Source: https://nginx.org/en/docs/http/ngx_http_upstream_module.html#keepalive
#### 常见问题
- **这是 nginx 的 bug 吗？** 几乎从来不是。这条日志的意思是「后端先挂了电话」，要去后端日志里找原因。
- **用户看到的是 502 还是下载中断？** 后端在响应头发出之前断开，nginx 返回 502；响应头已经发给客户端之后才断开，用户看到的是页面不完整或下载中断。

### Nginx (13: Permission denied) 权限错误排查
页面: https://nginx.cc/zh/errors/permission-denied · 最后核对: 2026-11-14

**快速答案:** 13: Permission denied 出现在读文件、连 socket、写日志或绑定端口时，原因是运行用户没有权限、父目录不可进入、socket 属主不对，或 SELinux 拦截。
**最常见原因:** 网站目录在 /home/用户 或 /root 下，父目录没有 x 权限。
**先这样改:** 让父目录可进入
```nginx
chmod o+x /home/deploy /home/deploy/site
# 更好的做法：网站放到 /var/www，属主部署用户，组为 www-data
```

#### 典型日志
```
open() "/home/deploy/site/index.html" failed (13: Permission denied)
connect() to unix:/run/php/php8.3-fpm.sock failed (13: Permission denied) while connecting to upstream
bind() to 0.0.0.0:80 failed (13: Permission denied)
open() "/var/log/nginx/access.log" failed (13: Permission denied)
```
#### 常见原因
1. 网站目录在 /home/用户 或 /root 下，父目录没有 x 权限。
2. PHP-FPM socket 的 listen.owner/listen.group 不是 nginx 的运行用户。
3. 非 root 运行 nginx 却要绑定 1024 以下端口。
4. SELinux 阻止读取非标准目录或连接 socket。
#### 排查命令
- `ps -o user= -C nginx | sort | uniq -c` — worker 进程以哪个用户运行
- `namei -l /home/deploy/site/index.html` — 逐级权限
- `ls -l /run/php/*.sock` — socket 属主
- `ausearch -m avc -ts recent | tail` — SELinux 拦截记录
#### 修复配置
PHP-FPM socket 属主:
```nginx
; /etc/php/8.3/fpm/pool.d/www.conf
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
; RHEL 系改为 nginx，然后重启 php-fpm
```
SELinux:
```nginx
semanage fcontext -a -t httpd_sys_content_t '/srv/site(/.*)?'
restorecon -Rv /srv/site
setsebool -P httpd_can_network_connect 1   # 需要连后端端口时
```
#### 关键事实与出处
- worker 进程以 user 指令指定的用户和组运行；不写时默认 nobody nobody，所以要看 nginx.conf 顶部那一行。 Source: https://nginx.org/en/docs/ngx_core_module.html#user
#### 常见问题
- **把 nginx 的 user 改成 root 行不行？** 不要。worker 以 root 运行，任何漏洞都直接拿到整台机器。应该修正文件和 socket 的权限。
- **chmod -R 777 能解决吗？** 不要。777 让任何用户都能改你的文件。正确做法是让 nginx 用户对路径上每一级目录有 x 权限、对文件有 r 权限（常见是目录 755、文件 644），用 namei -l 逐级检查。

### Nginx 400 Request Header Or Cookie Too Large 解决方法
页面: https://nginx.cc/zh/errors/400-request-header-too-large · 最后核对: 2026-11-14

**快速答案:** 400「Request Header Or Cookie Too Large」表示某一行请求头（多半是 Cookie）比 large_client_header_buffers 的单个缓冲区（默认 8k）还大。先清掉这个域名的 Cookie 确认原因，再在 http {} 里调到 16k 或 32k。
**最常见原因:** Cookie 越积越多：统计、A/B 测试、广告脚本各写一堆，或应用把会话 / JWT 整个存进 Cookie。
**先这样改:** 在 http 层调大请求头缓冲区
```nginx
http {
    large_client_header_buffers 4 32k;   # 默认 4 8k
}
```

#### 典型日志
```
client sent too long header line: "Cookie: …" while reading client request headers
client sent too long URI while reading client request line
```
#### 常见原因
1. Cookie 越积越多：统计、A/B 测试、广告脚本各写一堆，或应用把会话 / JWT 整个存进 Cookie。
2. 单点登录带来很长的 Authorization 头。
3. URL 查询串太长时返回的是 414 Request-URI Too Large，受同一个指令控制。
4. 只在某个非默认 server 里调大：请求头开始解析时还没选出 server，可能用的是默认 server 的值。
#### 排查命令
- `grep 'too long header line' /var/log/nginx/error.log | tail -3` — 这条日志是 info 级别，error_log 级别高于 info 时看不到
- `curl -s -o /dev/null -w '%{http_code}\n' -H "Cookie: big=$(head -c 12000 /dev/zero | tr '\0' x)" https://example.com/` — 构造一个 12KB 的 Cookie 复现
- `nginx -T 2>/dev/null | grep -n large_client_header_buffers` — 现在生效的值和位置
#### 修复配置
应用侧：别把大数据塞进 Cookie:
```nginx
# 会话数据放服务端（Redis / 数据库），Cookie 里只留会话 ID
# 清理不用的统计和 A/B 测试 Cookie
```
#### 关键事实与出处
- large_client_header_buffers 默认 4 8k：一行请求头不能超过一个缓冲区，否则返回 400；请求行超出则返回 414。 Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#large_client_header_buffers
- 在 server 层设置时，可能使用默认 server 的值。 Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#large_client_header_buffers
#### 常见问题
- **为什么只有部分用户出现？** 只有 Cookie 积累得特别多的浏览器才会超出 8k，换个浏览器或无痕窗口通常就正常，这正好说明是 Cookie 的问题。
- **调到多大合适？** 16k 或 32k 足够绝大多数站点。再往上调只是掩盖应用往 Cookie 里塞太多数据的问题，还会增加每个连接的内存。

### Nginx 499 Client Closed Request 是什么，怎么处理
页面: https://nginx.cc/zh/errors/499-client-closed-request · 最后核对: 2026-11-14

**快速答案:** 499 是 nginx 自己定义的状态码，只出现在访问日志里：客户端在 nginx 回应之前就断开了。大量 499 通常说明后端太慢、前面的 CDN 或负载均衡先超时放弃了。先查慢请求，再让各层超时保持一致。
**最常见原因:** 后端处理太慢，用户等不及刷新或关闭了页面。
**先这样改:** 记录耗时，找出慢请求
```nginx
log_format timed '$remote_addr [$time_local] "$request" $status '
                 'rt=$request_time urt=$upstream_response_time';
access_log /var/log/nginx/timed.log timed;
```

#### 典型日志
```
203.0.113.7 - - [14/Nov/2026:10:00:00 +0800] "POST /api/export HTTP/1.1" 499 0 "-" "Mozilla/5.0"
epoll_wait() reported that client prematurely closed connection, so upstream connection is closed too while sending request to upstream
```
#### 常见原因
1. 后端处理太慢，用户等不及刷新或关闭了页面。
2. 前面的 CDN / 负载均衡 / API 网关超时比后端处理时间短，先断开了到 nginx 的连接。
3. 健康检查或监控的超时设得太短。
4. 客户端代码主动取消请求（前端切换页面时 abort）。
#### 排查命令
- `awk '$9==499' /var/log/nginx/access.log | awk '{print $7}' | sort | uniq -c | sort -rn | head` — 哪些路径 499 最多（默认 combined 日志格式）
- `awk '$9==499' /var/log/nginx/access.log | wc -l` — 499 的总量，和平时对比
- `time curl -s -o /dev/null http://127.0.0.1:3000/api/export` — 直接测后端耗时
#### 修复配置
长任务让后端跑完（可选）:
```nginx
location /api/export {
    proxy_ignore_client_abort on;   # 客户端断开后仍等后端处理完
    proxy_read_timeout 300s;
    proxy_pass http://127.0.0.1:3000;
}
```
#### 关键事实与出处
- proxy_ignore_client_abort 默认 off：客户端断开时 nginx 也会关闭到后端的连接。 Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ignore_client_abort
- $request_time 从读到客户端第一个字节开始计时，单位秒，精确到毫秒。 Source: https://nginx.org/en/docs/http/ngx_http_log_module.html#var_request_time
#### 常见问题
- **499 是错误吗，要不要处理？** 少量 499 很正常（用户关页面）。集中在某几个接口、或在 CDN 超时附近大量出现时，才说明后端太慢需要处理。
- **为什么浏览器里看不到 499？** 因为连接已经断了，499 没有发给任何人，只写在 nginx 的访问日志里。

### Nginx 500：rewrite or internal redirection cycle 解决方法
页面: https://nginx.cc/zh/errors/500-rewrite-cycle · 最后核对: 2026-11-14

**快速答案:** 日志里的 “rewrite or internal redirection cycle” 表示请求在 nginx 内部反复跳转超过 10 次，最后返回 500。最常见的是 try_files 的回退目标（比如 /index.html）本身不存在，又落回同一个 location。先确认 root 和入口文件路径，再给回退加上 =404 兜底。
**最常见原因:** try_files 回退到 /index.html 或 /index.php，但 root 指错了目录，入口文件不存在。
**先这样改:** 回退链最后加 =404
```nginx
location / {
    root /var/www/site/dist;   # 确认 index.html 就在这里
    try_files $uri $uri/ /index.html =404;
}
```

#### 典型日志
```
rewrite or internal redirection cycle while internally redirecting to "/index.html"
rewrite or internal redirection cycle while processing "/index.php"
```
#### 常见原因
1. try_files 回退到 /index.html 或 /index.php，但 root 指错了目录，入口文件不存在。
2. rewrite 规则没有 last / break，改写后的 URI 又匹配同一条规则。
3. error_page 指向的页面本身也报同样的错误。
4. 前端构建产物还没上传（dist 目录为空）。
#### 排查命令
- `grep 'redirection cycle' /var/log/nginx/error.log | tail -3` — 看循环到了哪个 URI
- `nginx -T 2>/dev/null | grep -nE 'root|try_files|rewrite|error_page'` — 相关指令一览
- `ls -l /var/www/site/index.html` — 回退目标是否真的存在
#### 修复配置
rewrite 要么 last 要么 break:
```nginx
location /blog/ {
    rewrite ^/blog/(.*)$ /index.php?p=$1 last;
}
```
#### 关键事实与出处
- try_files 只检查最后一个参数之前的文件；最后一个参数会触发内部重定向，或是 =code。 Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#try_files
- rewrite 的 last 会用新 URI 重新匹配 location，break 则在当前 location 内继续处理。 Source: https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite
#### 常见问题
- **为什么是 500 而不是 404？** nginx 把超过 10 次的内部重定向当作配置错误，所以返回 500。修好路径后就会变成正常的 200 或 404。
- **SPA 刷新页面就 500 怎么办？** 通常是 root 没有指向构建目录（dist / build），导致 /index.html 找不到。改对 root 即可。

### Nginx + PHP-FPM「File not found」/ Primary script unknown
页面: https://nginx.cc/zh/errors/php-fpm-primary-script-unknown · 最后核对: 2026-11-14

**快速答案:** 页面只显示 “File not found.”、日志里是 “Primary script unknown”，说明 PHP-FPM 按 SCRIPT_FILENAME 找不到 PHP 文件。九成是 SCRIPT_FILENAME 没写或 $document_root 不对（root 写在了 location 里），其余是 PHP-FPM 没权限读文件或 open_basedir 限制。
**最常见原因:** 没有设置 SCRIPT_FILENAME：只 include fastcgi_params 不够（Debian 的 fastcgi.conf / snippets/fastcgi-php.conf 才带上它）。
**先这样改:** root 放 server 层，显式设置 SCRIPT_FILENAME
```nginx
server {
    root /var/www/site;   # 放在 server 层，所有 location 都能继承
    index index.php index.html;

    location ~ \.php$ {
        try_files $uri =404;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }
}
```

#### 典型日志
```
FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream
FastCGI sent in stderr: "PHP message: PHP Warning:  Unknown: open_basedir restriction in effect."
```
#### 常见原因
1. 没有设置 SCRIPT_FILENAME：只 include fastcgi_params 不够（Debian 的 fastcgi.conf / snippets/fastcgi-php.conf 才带上它）。
2. root 只写在 location / 里，PHP 的 location 继承不到，$document_root 变成默认的 html 目录。
3. PHP-FPM 进程用户（如 www-data）读不了网站目录。
4. PHP-FPM 跑在 Docker 容器里，容器内的路径和 nginx 看到的路径不一样。
5. php.ini 或池配置的 open_basedir 不包含网站目录。
#### 排查命令
- `grep -E 'Primary script unknown|open_basedir' /var/log/nginx/error.log | tail -3` — 确认是哪一种
- `nginx -T 2>/dev/null | grep -nE 'root|SCRIPT_FILENAME|fastcgi_pass|include'` — SCRIPT_FILENAME 和 root 在哪里
- `sudo -u www-data test -r /var/www/site/index.php && echo readable` — PHP-FPM 用户能否读到文件
#### 修复配置
PHP-FPM 在容器里：用容器内的路径:
```nginx
fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name;   # 容器内的网站目录
fastcgi_pass php:9000;
```
#### 关键事实与出处
- $fastcgi_script_name 是请求 URI（以 / 结尾时加上 fastcgi_index 的值）。 Source: https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#var_fastcgi_script_name
- fastcgi_param 只在当前层没有定义任何 fastcgi_param 时才从上一层继承。 Source: https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_param
#### 常见问题
- **fastcgi_params 和 fastcgi.conf 有什么区别？** fastcgi.conf 比 fastcgi_params 多了一行 SCRIPT_FILENAME。用 fastcgi_params 时必须自己写 SCRIPT_FILENAME。
- **为什么只有 PHP 文件 404，静态文件正常？** 静态文件由 nginx 按 root 直接读取；PHP 文件由 PHP-FPM 按 SCRIPT_FILENAME 去找，两边路径或权限不一致就会只坏 PHP。

### Nginx 502：upstream sent too big header 解决方法
页面: https://nginx.cc/zh/errors/upstream-sent-too-big-header · 最后核对: 2026-11-14

**快速答案:** “upstream sent too big header” 表示后端返回的响应头（通常是很多或很大的 Set-Cookie、长 Location）超过了 proxy_buffer_size / fastcgi_buffer_size（默认一个内存页，4k 或 8k），nginx 只能返回 502。把对应的 buffer_size 调到 16k～32k 即可，同时检查应用为什么发这么大的头。
**最常见原因:** 登录、SSO 回调时一次写入多个大 Cookie。
**先这样改:** 反向代理（proxy_pass）
```nginx
proxy_buffer_size 16k;
proxy_buffers 8 16k;
proxy_busy_buffers_size 32k;
```

#### 典型日志
```
upstream sent too big header while reading response header from upstream
upstream sent too big header while reading response header from upstream, client: 203.0.113.7, server: example.com, request: "POST /login HTTP/1.1", upstream: "fastcgi://unix:/run/php/php8.3-fpm.sock:"
```
#### 常见原因
1. 登录、SSO 回调时一次写入多个大 Cookie。
2. 应用把调试信息、权限列表放进响应头。
3. WordPress 插件、Magento 等在后台页面发出很长的 Link / Set-Cookie 头。
#### 排查命令
- `grep 'too big header' /var/log/nginx/error.log | tail -3` — upstream 字段告诉你是 proxy 还是 fastcgi
- `curl -s -D - -o /dev/null http://127.0.0.1:3000/login | wc -c` — 绕过 nginx 量一下响应头大小
#### 修复配置
PHP-FPM（fastcgi_pass）:
```nginx
fastcgi_buffer_size 32k;
fastcgi_buffers 16 16k;
fastcgi_busy_buffers_size 32k;
```
#### 关键事实与出处
- proxy_buffer_size 用于读取响应的第一部分（响应头），默认等于一个内存页：4k 或 8k。 Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_buffer_size
- fastcgi_buffer_size 对 FastCGI 起同样的作用，默认同样是 4k 或 8k。 Source: https://nginx.org/en/docs/http/ngx_http_fastcgi_module.html#fastcgi_buffer_size
#### 常见问题
- **调大 buffer 有副作用吗？** 每个连接多占一点内存。16k～32k 对绝大多数站点没有影响；需要上百 KB 时更应该修应用。
- **busy_buffers_size 为什么也要改？** proxy_busy_buffers_size 不能小于 proxy_buffer_size 和单个 proxy_buffers 中较大的那个，否则 nginx -t 会报错。

### Nginx 报 no resolver defined to resolve 的原因与解决
页面: https://nginx.cc/zh/errors/no-resolver-defined · 最后核对: 2026-11-14

**快速答案:** proxy_pass 里用了变量（如 proxy_pass https://$host 或 $backend）时，域名要在请求时解析，而 nginx 不读 /etc/resolv.conf，必须用 resolver 指令指定 DNS 服务器；没写就会报 “no resolver defined” 并返回 502。加上 resolver，或者改用 upstream / 不含变量的 proxy_pass。
**最常见原因:** proxy_pass 中含变量，没有配置 resolver。
**先这样改:** 指定 resolver
```nginx
http {
    resolver 1.1.1.1 8.8.8.8 valid=300s ipv6=off;
    resolver_timeout 5s;
}
```

#### 典型日志
```
no resolver defined to resolve api.example.com, client: 203.0.113.7
api.example.com could not be resolved (3: Host not found)
```
#### 常见原因
1. proxy_pass 中含变量，没有配置 resolver。
2. Docker 中用服务名代理：需要 Docker 内置 DNS 127.0.0.11。
3. resolver 写成了 127.0.0.53（systemd-resolved）但容器里没有它。
#### 排查命令
- `grep -E 'no resolver|could not be resolved' /var/log/nginx/error.log | tail -3` — 确认报错
- `nginx -T 2>/dev/null | grep -nE 'resolver|proxy_pass .*\$'` — 哪些 proxy_pass 用了变量
- `grep nameserver /etc/resolv.conf` — 系统用的 DNS（nginx 不会自动读取）
#### 修复配置
Docker 里:
```nginx
resolver 127.0.0.11 valid=30s;   # Docker 内置 DNS
set $backend http://app:3000;
proxy_pass $backend;
```
不需要动态解析时：去掉变量:
```nginx
upstream api {
    server api.example.com:443;
}
proxy_pass https://api;   # 启动时解析一次
```
#### 关键事实与出处
- proxy_pass 的地址含变量时，域名在运行时解析，需要配置 resolver（除非能匹配到已定义的 upstream）。 Source: https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass
- resolver 默认按 TTL 缓存结果，可用 valid 参数覆盖。 Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#resolver
#### 常见问题
- **为什么不含变量时就不需要 resolver？** 不含变量时 nginx 在启动和 reload 时就用系统解析器把域名解析好了；代价是 IP 变了要 reload 才会更新。
- **valid=300s 是什么意思？** 覆盖 DNS 记录的 TTL，缓存 300 秒。

### could not build server_names_hash 的解决方法
页面: https://nginx.cc/zh/errors/server-names-hash-bucket-size · 最后核对: 2026-11-14

**快速答案:** nginx -t 报 “could not build server_names_hash, you should increase server_names_hash_bucket_size” 是因为某个 server_name 太长（或域名太多），默认的哈希桶装不下。在 http {} 里把 server_names_hash_bucket_size 设为 64（仍不行就 128），域名特别多时再调大 server_names_hash_max_size。
**最常见原因:** 域名很长（多级子域名、长随机前缀）。
**先这样改:** 在 http 层调大
```nginx
http {
    server_names_hash_bucket_size 64;   # 不够再改 128
    server_names_hash_max_size 1024;    # 域名很多时
}
```

#### 典型日志
```
nginx: [emerg] could not build server_names_hash, you should increase server_names_hash_bucket_size: 32
nginx: [warn] could not build optimal server_names_hash, you should increase either server_names_hash_max_size: 512 or server_names_hash_bucket_size: 64
```
#### 常见原因
1. 域名很长（多级子域名、长随机前缀）。
2. 一台机器上有成百上千个 server_name。
3. 桶大小默认取决于 CPU 缓存行（32、64 或 128），换了机器就可能突然报错。
#### 排查命令
- `nginx -t` — 看报的是 emerg（必须改）还是 warn（建议改）
- `nginx -T 2>/dev/null | grep -o 'server_name[^;]*' | awk '{for(i=2;i<=NF;i++) print length($i), $i}' | sort -rn | head` — 最长的域名
#### 修复配置
#### 关键事实与出处
- server_names_hash_bucket_size 默认 32|64|128，取决于处理器缓存行大小。 Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#server_names_hash_bucket_size
- server_names_hash_max_size 默认 512。 Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#server_names_hash_max_size
- 官方建议：域名很多时先把 server_names_hash_max_size 调到接近域名数量；遇到 bucket_size 报错时改成下一个 2 的幂（如 32 → 64）。 Source: https://nginx.org/en/docs/http/server_names.html#optimization
#### 常见问题
- **写在 server 里可以吗？** 不行，这两个指令只能写在 http 层，写在 server 里 nginx -t 会报 “directive is not allowed here”。
- **warn 也要处理吗？** warn 不影响启动，只是查找效率稍差。按提示调大其中一个值即可消除。

### Nginx 警告 conflicting server name … ignored 怎么处理
页面: https://nginx.cc/zh/errors/conflicting-server-name · 最后核对: 2026-11-14

**快速答案:** “conflicting server name "example.com" on 0.0.0.0:80, ignored” 表示两个 server 块在同一个地址端口上写了同一个 server_name，后读到的那个被忽略，于是你改的配置可能根本没生效。用 nginx -T 找出重复的 server_name，删掉多余的文件（常见是 default、备份文件 .bak、sites-enabled 里重复的软链接）。
**最常见原因:** sites-enabled 里留着备份文件（example.conf.bak、example.conf~），include *.conf 以外的通配会把它们也读进来。
**先这样改:** 删掉重复的站点文件
```nginx
rm /etc/nginx/sites-enabled/example.conf.bak
nginx -t && systemctl reload nginx
```

#### 典型日志
```
nginx: [warn] conflicting server name "example.com" on 0.0.0.0:80, ignored
nginx: [warn] conflicting server name "example.com" on [::]:443, ignored
```
#### 常见原因
1. sites-enabled 里留着备份文件（example.conf.bak、example.conf~），include *.conf 以外的通配会把它们也读进来。
2. 同一站点在 conf.d 和 sites-enabled 各有一份。
3. certbot --nginx 改写后又手动加了一个同名 server。
#### 排查命令
- `nginx -T 2>/dev/null | grep -nE '^# configuration file|server_name'` — 每个 server_name 来自哪个文件
- `ls -la /etc/nginx/sites-enabled/ /etc/nginx/conf.d/` — 找备份文件和重复软链接
#### 修复配置
只 include .conf 文件:
```nginx
# 先把站点文件都改成 .conf 结尾（Debian 自带的 default 没有扩展名）
http {
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*.conf;
}
```
#### 关键事实与出处
- nginx 先按 listen 的地址端口、再按 server_name 选择 server；同一端口上没有匹配时使用 default_server。 Source: https://nginx.org/en/docs/http/request_processing.html
- nginx -T 会测试配置并打印所有被加载的配置文件。 Source: https://nginx.org/en/docs/switches.html
#### 常见问题
- **只是警告，可以不管吗？** 不建议。被忽略的那个 server 可能正是你刚改的那份，表现为「怎么改都不生效」。
- **80 和 443 各一个同名 server 算冲突吗？** 不算。冲突指的是同一个地址端口上的同名 server。

### Nginx 405 Not Allowed：POST 请求被拒绝的原因
页面: https://nginx.cc/zh/errors/405-not-allowed · 最后核对: 2026-11-14

**快速答案:** nginx 返回 405 Not Allowed，最常见的是 POST（或 PUT、DELETE）请求落到了静态文件上：静态文件只接受 GET 和 HEAD。通常是接口路径没有被 proxy_pass / fastcgi_pass 接走，被 try_files 回退到了 index.html。把接口 location 单独交给后端即可。
**最常见原因:** SPA 的 try_files $uri /index.html 把 POST /api/... 也回退到了 index.html。
**先这样改:** 接口单独交给后端
```nginx
location /api/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
}
location / {
    try_files $uri $uri/ /index.html;
}
```

#### 典型日志
```
"POST /api/login HTTP/1.1" 405 157
405 Not Allowed
```
#### 常见原因
1. SPA 的 try_files $uri /index.html 把 POST /api/... 也回退到了 index.html。
2. 接口的 location 前缀写错（/api 和 /api/ 不一致），请求没进到 proxy_pass。
3. 表单提交到 .html 静态页。
4. 配置了 limit_except GET 等方法限制。
#### 排查命令
- `curl -si -X POST https://example.com/api/login | head -5` — 看是 nginx 还是后端返回的 405
- `nginx -T 2>/dev/null | grep -nE 'location|try_files|proxy_pass|limit_except'` — 请求会匹配到哪个 location
#### 修复配置
#### 关键事实与出处
- limit_except 限制 location 内允许的 HTTP 方法；允许 GET 时也会自动允许 HEAD。 Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#limit_except
- error_page 指向 URI 时做内部重定向，并把 GET、HEAD 以外的请求方法改成 GET；指向命名 location（error_page 405 = @名字）则不改 URI 和方法。 Source: https://nginx.org/en/docs/http/ngx_http_core_module.html#error_page
#### 常见问题
- **能不能用 error_page 405 =200 $uri 绕过？** 能让页面显示出来，但 POST 的数据被直接丢掉，接口并没有被调用。应该把请求交给真正处理它的后端。
- **怎么区分是 nginx 还是应用返回的 405？** nginx 的 405 页面底部有一行 nginx（或版本号），Server 头也是 nginx；应用的 405 通常带有 Allow 头和应用自己的错误格式。

### Nginx unknown directive 报错：http2、brotli、quic 等
页面: https://nginx.cc/zh/errors/unknown-directive · 最后核对: 2026-11-14

**快速答案:** nginx -t 报 “unknown directive "http2"” 之类，说明当前 nginx 不认识这个指令：要么版本太旧（http2 on 需要 1.25.1+），要么所需模块没编译或没加载（brotli、headers-more 是第三方模块），要么是拼写错误、不可见字符。先看 nginx -V 的版本和模块，再改写法或装模块。
**最常见原因:** 发行版自带的 nginx 太旧：Debian 12 是 1.22，Ubuntu 24.04 是 1.24，没有 http2 on;。
**先这样改:** 旧版本的 HTTP/2 写法
```nginx
# nginx < 1.25.1
listen 443 ssl http2;
# nginx ≥ 1.25.1
listen 443 ssl;
http2 on;
```

#### 典型日志
```
nginx: [emerg] unknown directive "http2" in /etc/nginx/sites-enabled/example.conf:4
nginx: [emerg] unknown directive "brotli" in /etc/nginx/nginx.conf:30
nginx: [emerg] unknown directive "more_set_headers" in /etc/nginx/conf.d/security.conf:2
```
#### 常见原因
1. 发行版自带的 nginx 太旧：Debian 12 是 1.22，Ubuntu 24.04 是 1.24，没有 http2 on;。
2. brotli、more_set_headers 等第三方模块没安装，或 load_module 没写。
3. listen … quic 需要带 --with-http_v3_module 编译的 nginx（1.25.0+）。
4. 从网页复制配置带进了全角空格、零宽字符或中文标点。
#### 排查命令
- `nginx -V 2>&1 | tr ' ' '\n' | grep -E 'version|http_v2|http_v3|brotli|headers-more'` — 版本和编译进来的模块
- `ls /etc/nginx/modules-enabled/ /usr/lib/nginx/modules/ 2>/dev/null` — 可加载的动态模块
- `grep -nP '[^\x00-\x7F]' /etc/nginx/sites-enabled/example.conf` — 找出非 ASCII 字符
#### 修复配置
Debian 12+ 安装 brotli 模块:
```nginx
apt install libnginx-mod-http-brotli-filter libnginx-mod-http-brotli-static
nginx -t && systemctl reload nginx
```
或者换成 nginx.org 官方源的新版本:
```nginx
curl -fsSL nginx.cc/install | sudo bash -s -- --dry-run
```
#### 关键事实与出处
- http2 指令出现在 nginx 1.25.1。 Source: https://nginx.org/en/docs/http/ngx_http_v2_module.html#http2
- HTTP/3 模块从 1.25.0 起提供，默认不编译，需要 --with-http_v3_module。 Source: https://nginx.org/en/docs/http/ngx_http_v3_module.html
#### 常见问题
- **“directive is not allowed here” 是同一个问题吗？** 不是。那表示指令存在但写错了层级（比如把 server_names_hash_bucket_size 写进了 server），看官方文档里的 Context 一栏。
- **nginx.org 官方包有 brotli 吗？** brotli 不是 nginx 自带模块，需要单独安装第三方模块包或自行编译；Debian 12 起官方仓库有 libnginx-mod-http-brotli-filter。

### Nginx cannot load certificate：证书文件不存在或与私钥不匹配
页面: https://nginx.cc/zh/errors/cannot-load-certificate · 最后核对: 2026-11-14

**快速答案:** nginx -t 报 “cannot load certificate … No such file or directory”，最常见的是还没签证书就先写了 ssl_certificate（先有鸡还是先有蛋）；“key values mismatch” 则是证书和私钥不是一对。新站先用纯 HTTP 配置签证书，签好再切 HTTPS；不匹配时用 openssl 对比两者的公钥。
**最常见原因:** 新站直接用了带 ssl_certificate 的完整配置，证书还没签发。
**先这样改:** 先 HTTP 签证书，再切 HTTPS
```nginx
server {
    listen 80;
    server_name example.com;
    location /.well-known/acme-challenge/ { root /var/www/_letsencrypt; }
}
# certbot certonly --webroot -w /var/www/_letsencrypt -d example.com
# 签好后再加上 listen 443 ssl 和 ssl_certificate
```

#### 典型日志
```
nginx: [emerg] cannot load certificate "/etc/letsencrypt/live/example.com/fullchain.pem": BIO_new_file() failed (SSL: error:80000002:system library::No such file or directory…)
nginx: [emerg] SSL_CTX_use_PrivateKey("/etc/ssl/private/example.key") failed (SSL: error:05800074:x509 certificate routines::key values mismatch)
```
#### 常见原因
1. 新站直接用了带 ssl_certificate 的完整配置，证书还没签发。
2. 路径写错：live/ 下的目录名带了 -0001 后缀（重复签发时 certbot 会新建目录）。
3. 证书更新了但私钥用的还是旧的，或把别的域名的私钥配进来了。
4. nginx 用户读不了私钥文件（权限 600 属主不对）。
#### 排查命令
- `ls -l /etc/letsencrypt/live/` — 证书目录的真实名字
- `certbot certificates` — certbot 管理的证书和路径
- `openssl x509 -noout -pubkey -in fullchain.pem | sha256sum; openssl pkey -pubout -in privkey.pem | sha256sum` — 两个哈希相同才是一对
#### 修复配置
证书与私钥成对引用:
```nginx
ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
```
#### 关键事实与出处
- ssl_certificate 指定 PEM 格式证书；有中间证书时应放在同一文件里、服务器证书之后。 Source: https://nginx.org/en/docs/http/ngx_http_ssl_module.html#ssl_certificate
- Certbot 的 webroot 插件把验证文件写到 <webroot>/.well-known/acme-challenge/。 Source: https://eff-certbot.readthedocs.io/en/stable/using.html#webroot
#### 常见问题
- **为什么 certbot --nginx 也失败？** certbot 需要先让 nginx 跑起来，而 nginx 因为找不到证书起不来。先注释掉 443 的 server 或改用阶段一配置。
- **用 cert.pem 还是 fullchain.pem？** 用 fullchain.pem。只用 cert.pem 会缺中间证书，部分客户端会报证书不受信任。

## CMS rewrite rules: sources

- WordPress — Checked against official docs: developer.wordpress.org · Nginx <https://developer.wordpress.org/advanced-administration/server/web-server/nginx/> · https://nginx.cc/en/rewrite/wordpress
- Typecho — Checked against official docs: docs.typecho.org · Server setup <https://docs.typecho.org/servers> · https://nginx.cc/en/rewrite/typecho
- Z-Blog PHP — Community-standard rules: zblogcn.com (rules generated by the admin “static URL options” plugin) <https://www.zblogcn.com/> · https://nginx.cc/en/rewrite/zblog
- emlog — Community-standard rules: emlog.net (admin “Settings → SEO”) <https://www.emlog.net/> · https://nginx.cc/en/rewrite/emlog
- Halo — Checked against official docs: docs.halo.run · FAQ (413 / reverse proxy) <https://docs.halo.run/guide/faq>; halo.run · fixing 413 <https://www.halo.run/archives/fix-413-request-entity-too-large> · https://nginx.cc/en/rewrite/halo
- Ghost — Checked against official repo/sample: Ghost-CLI nginx template <https://github.com/TryGhost/Ghost-CLI/blob/main/extensions/nginx/templates/nginx-ssl.conf>; ghost.org/docs/config <https://ghost.org/docs/config/> · https://nginx.cc/en/rewrite/ghost
- Discuz! X — Community-standard rules: Discuz! admin “Global → SEO → Static URLs → view current rewrite rules” <https://www.discuz.vip/> · https://nginx.cc/en/rewrite/discuz
- phpBB — Checked against official repo/sample: phpBB docs/nginx.sample.conf <https://github.com/phpbb/phpbb/blob/master/phpBB/docs/nginx.sample.conf> · https://nginx.cc/en/rewrite/phpbb
- DedeCMS — Community-standard rules: DedeCMS admin “System → Core settings → rewrite” (community rules) <https://www.dedecms.com/> · https://nginx.cc/en/rewrite/dedecms
- EmpireCMS — Community-standard rules: EmpireCMS 7.5 admin “System → rewrite settings” (community rules) <http://www.phome.net/> · https://nginx.cc/en/rewrite/empirecms
- PbootCMS — Community-standard rules: PbootCMS help docs (3.x rewrite, community rules) <https://www.pbootcms.com/> · https://nginx.cc/en/rewrite/pbootcms
- Drupal — Checked against official repo/sample: NGINX wiki recipe · Drupal <https://github.com/nginxinc/nginx-wiki/blob/master/source/start/topics/recipes/drupal.rst>; drupal.org · Web server requirements <https://www.drupal.org/docs/getting-started/system-requirements/web-server-requirements> · https://nginx.cc/en/rewrite/drupal
- Joomla — Checked against official docs: docs.joomla.org · Nginx <https://docs.joomla.org/Nginx> · https://nginx.cc/en/rewrite/joomla
- MediaWiki — Checked against official docs: mediawiki.org · Manual:Short URL/Nginx <https://www.mediawiki.org/wiki/Manual:Short_URL/Nginx> · https://nginx.cc/en/rewrite/mediawiki
- ThinkPHP — Checked against official repo/sample: ThinkPHP 8 docs · URL rewriting <https://doc.thinkphp.cn/v8_0/url_rewrite.html>; top-think/think public/.htaccess <https://github.com/top-think/think/blob/8.0/public/.htaccess> · https://nginx.cc/en/rewrite/thinkphp
- Laravel — Checked against official docs: laravel.com/docs · Deployment · Nginx <https://laravel.com/docs/12.x/deployment#nginx> · https://nginx.cc/en/rewrite/laravel
- Magento 2 — Checked against official repo/sample: magento2 nginx.conf.sample <https://github.com/magento/magento2/blob/2.4-develop/nginx.conf.sample> · https://nginx.cc/en/rewrite/magento
- PrestaShop — Checked against official docs: devdocs.prestashop-project.org · Configure Nginx <https://devdocs.prestashop-project.org/9/basics/installation/advanced/nginx/> · https://nginx.cc/en/rewrite/prestashop
- OpenCart — Checked against official repo/sample: OpenCart 3.0 .htaccess.txt (converted from the official Apache rules) <https://github.com/opencart/opencart/blob/3.0.x.x_Maintenance/upload/.htaccess.txt> · https://nginx.cc/en/rewrite/opencart
- WHMCS — Checked against official repo/sample: docs.whmcs.com · Friendly URLs (official Apache rules, converted to nginx) <https://docs.whmcs.com/9-0/system/general-settings/general-settings-general/> · https://nginx.cc/en/rewrite/whmcs
- Nextcloud — Checked against official docs: docs.nextcloud.com · NGINX configuration <https://docs.nextcloud.com/server/latest/admin_manual/installation/nginx.html> · https://nginx.cc/en/rewrite/nextcloud

## Config generator scenarios

- Static site (Plain files with asset caching): https://nginx.cc/en/gen?s=static
- Reverse proxy (Forward to any backend port, WebSocket-ready): https://nginx.cc/en/gen?s=reverse-proxy
- PHP-FPM (Generic PHP site (index.php front controller)): https://nginx.cc/en/gen?s=php
- WordPress (PHP-FPM with WordPress hardening and login throttling): https://nginx.cc/en/gen?s=wordpress
- Node.js (Express/Next.js/Nuxt with WebSocket and static caching): https://nginx.cc/en/gen?s=node
- Django / Python (Gunicorn/Uvicorn proxy plus /static and /media): https://nginx.cc/en/gen?s=django
- Load balancing (Several backends with passive health checks): https://nginx.cc/en/gen?s=load-balance
- WebSocket (Proxy ws/wss long-lived connections): https://nginx.cc/en/gen?s=websocket
- HTTPS redirect (HTTP→HTTPS and www/apex canonicalisation): https://nginx.cc/en/gen?s=https-redirect
- Single-page app (Vue/React history routing to index.html): https://nginx.cc/en/gen?s=spa
- Compression & caching (gzip/Brotli and asset caching, split into http- and server-level parts): https://nginx.cc/en/gen?s=gzip-cache
- Rate limiting (Per-IP request limits returning 429): https://nginx.cc/en/gen?s=rate-limit
- nginx.conf tuning (Global tuning: workers, connections, sendfile, logging): https://nginx.cc/en/gen?s=nginx-conf

## Credits

Generator layout adapted from nginxconfig.io (MIT License, Copyright (c) 2020 DigitalOcean): https://github.com/digitalocean/nginxconfig.io — TLS profiles from Mozilla Server Side TLS: https://ssl-config.mozilla.org/
