server 块怎么写、fastcgi 参数怎么传、伪静态怎么配、502/500 怎么查。附一套可直接抄的 Nginx 配置片段。
Nginx 本身不执行 PHP,它通过 fastcgi_pass 把请求转发给 PHP-FPM 进程池。部署 Typecho 的核心是三件事:① Nginx server 块里 root 指向 Typecho 目录,index 加上 index.php;② location ~ \.php$ 块里 fastcgi_pass 到 PHP-FPM(TCP 127.0.0.1:9000 或 unix socket),include fastcgi_params,并显式设置 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;③ 加 location / 把不存在的路径重写到 index.php 实现伪静态。502 基本都是 PHP-FPM 没跑或 fastcgi_pass 地址写错;500 多半是缺 PHP 扩展(如 tokenizer/mbstring)或文件权限不对。
一次请求在两个进程间怎么走
Nginx 监听 80/443,按 server_name 和 URL 路径匹配 location。静态文件直接返回,PHP 文件转给 PHP-FPM。
Nginx 把 HTTP 请求转成 FastCGI 协议包,发给 PHP-FPM 监听的 TCP 端口或 unix socket。见 ngx_http_fastcgi_module 文档。
PHP-FPM master 进程拉起 worker,worker 执行 SCRIPT_FILENAME 指定的 PHP 脚本,把输出通过 FastCGI 返回给 Nginx。
Nginx 加上 HTTP 头、gzip、缓存控制,把结果发给浏览器。PHP 错误由 PHP-FPM 写入日志,Nginx 只能看到 5xx。
把 example.com 换成你的域名,root 换成 Typecho 实际目录
关键参数解释:$document_root 来自 ngx_http_core_module,见 官方文档;SCRIPT_FILENAME 必须指向真实文件路径,PHP-FPM 靠它找到要执行的脚本。
监听方式、进程数、用户权限
| 配置项 | 推荐值 | 说明 |
|---|---|---|
listen | 127.0.0.1:9000 或 unix socket | unix socket 更快、不占端口,Nginx 同机部署时推荐 |
user / group | nginx / nginx(或 www-data) | PHP-FPM worker 以该用户身份读文件,必须能读 Typecho 目录 |
pm | dynamic | 动态进程数,小内存机器省资源 |
pm.max_children | 5~10(1G 内存) | 按每个 worker 约 30~50 MB 估算 |
pm.start_servers | 2~4 | 启动时拉起的进程数 |
php_admin_value[error_log] | /var/log/php-fpm/error.log | PHP 错误日志,500 排查必看 |
完整配置项见 PHP 官方 php-fpm 配置文档。
让文章 URL 从 ?cid=1 变成 /archives/1/
location / { try_files $uri $uri/ /index.php$args; }if (!-e $request_filename) { rewrite ^(.*)$ /index.php$1 last; }/archives/[cid]/https://example.com/archives/1/ 应正常打开文章按顺序查,90% 的问题能定位
| 现象 | 最可能原因 | 排查命令/位置 |
|---|---|---|
| 502 Bad Gateway | PHP-FPM 没跑,或 fastcgi_pass 地址与 PHP-FPM 监听地址不一致 | ps aux | grep php-fpm;看 Nginx error.log;对比 listen 配置 |
| 502 + connect() refused | Nginx 配置 127.0.0.1:9000 但 PHP-FPM 监听的是 unix socket |
改 fastcgi_pass 为对应 socket 路径,或改 PHP-FPM listen 为 TCP |
| 500 Internal Server Error | PHP 代码抛异常;常见是缺 php-tokenizer / php-mbstring 扩展 | 看 PHP-FPM error.log(见上表路径);Alpine 上 apk add php83-tokenizer php83-mbstring |
| 404 on 伪静态 URL | try_files / rewrite 没生效,或 Nginx 配置没 reload | nginx -t && nginx -s reload;确认 location / 块存在 |
| CSS/JS 404 | root 路径不对,或 HTTP_HOST 没传给 PHP,Typecho 生成了错误 URL | 确认 fastcgi_param HTTP_HOST $host;;浏览器 F12 看静态文件 URL |
| 403 Forbidden | Typecho 目录权限不对,PHP-FPM 用户读不到文件 | chown -R nginx:nginx /var/www/typecho;目录至少 755,文件 644 |
fastcgi_pass 把请求转发给 PHP-FPM 进程,由 PHP-FPM 执行 PHP 脚本并返回结果。这是经典的 Nginx + PHP-FPM 架构。location / { try_files $uri $uri/ /index.php$args; },把不存在的路径内部重写到 index.php,由 Typecho 路由。也可以用 if (!-e $request_filename) { rewrite ^(.*)$ /index.php$1 last; }。ps aux | grep php-fpm),再看 Nginx 配置里 fastcgi_pass 的地址与 PHP-FPM 监听地址是否一致(127.0.0.1:9000 或 unix socket 路径),最后看 Nginx error.log 具体错误。