Menu Home

解决 Nginx 与 FastCGI 通信错误 “Primary script unknown”?

错误原因

接上篇解决了权限问题厚,wordpress依然报错 404 File not found 的提示信息。查看错误日志报告显示 FastCGI sent in stderr: “Primary script unknown” while reading response header from upstream 这样的错误信息。之所以出现这样的情况,是因为 nginx 将请求 uri 转发给 FastCGI 处理时, FastCGI 并没有接收到相应的 uri 参数。出现这样的错误大致分为以下三种。

1. 根目录配置错误

roy@localhost:/$ sudo vim /etc/nginx/sites-enabled/a.com
...
server {
    listen 443 ssl;
    server_name a.com;
    index index.html index.php;
    root /home/roy/www;

确认 /home/roy/www 目录正确

2. NGINX 用户与 php-fpm 用户不一致

roy@localhost:/$ sudo ps -ef | grep nginx
root        2384       1  0 Mar19 ?        00:00:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
www-data    2385    2384  0 Mar19 ?        00:00:22 nginx: worker process
www-data    2386    2384  0 Mar19 ?        00:00:00 nginx: worker process
roy         9511    9462  0 14:18 pts/3    00:00:00 grep --color=auto nginx
roy@localhost:/$ sudo ps -ef | grep php-fpm
root        1788       1  0 Mar19 ?        00:00:02 php-fpm: master process (/etc/php/8.1/fpm/php-fpm.conf)
www-data    7797    1788  0 09:54 ?        00:00:38 php-fpm: pool www
www-data    8169    1788  0 09:56 ?        00:00:37 php-fpm: pool www
www-data    8248    1788  0 10:18 ?        00:00:30 php-fpm: pool www
magth       9507    9462  0 14:18 pts/3    00:00:00 grep --color=auto php-fpm

可以看到 nginxphp-fpm 进程所属用户都是 www-data ,说明配置没问题。如果两个进程所属用户不同,需要修改配置文件:

roy@localhost:/$ sudo vim /etc/nginx/nginx.conf
...
user www-data
...
roy@localhost:/$ sudo vim /etc/php/8.1/php-fpm.d/www.conf
...
Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
user = www-data
group = www-data

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions.
; Default Values: user and group are set as the running user
;                 mode is set to 0660
listen.owner = www-data
listen.group = www-data
listen.mode = 0660
...

记得配置文件修改后,需要重启服务才能生效。

roy@localhost:/$ sudo systemctl restart nginx.service php8.1-fpm.service

3. 采用了默认的 fastcgi 配置信息

nginx 安装后默认的 fastcgi_param 配置信息是:

fastcgi_param  SCRIPT_FILENAME  /Scripts$fastcgi_script_name;

正确的配置应该为:

fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;

Categories: nginx ubuntu

Tagged as:

RoyAkon