Nginx

nginx 和 php-fpm:從上游讀取響應標頭時出現“主腳本未知”

  • October 22, 2021

我想將任何api/*路由傳遞給 php-fpm。特別是index.php當我使用 Symfony 時。這是唯一應該使用 php 的路由。其他任何內容都將從/usr/share/nginx/html/public(僅 HTML 文件和 CSS)載入。

我已經嘗試過了,但我收到了一個錯誤:

FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream

我的 nginx 配置如下:

upstream php {
 server php:9000;
}

server {
 listen 80 default_server;
 server_name impressive.local;
 index index.html index.php;
 root /usr/share/nginx/html/public;

 location /api {
   root /usr/share/nginx/html/api;
   try_files $uri /index.php;
 }

 location ~ \.php$ {
   fastcgi_pass php;
   fastcgi_split_path_info ^(.+\.php)(/.*)$;
   include fastcgi.conf;
 }
}

我收到以下錯誤:

php_1  | [13-Jan-2019 23:22:54] NOTICE: fpm is running, pid 1
php_1  | [13-Jan-2019 23:22:54] NOTICE: ready to handle connections
php_1  | 172.25.0.3 -  13/Jan/2019:23:22:57 +0000 "GET /api/index.php" 404
web_1  | 2019/01/13 23:22:57 [error] 10#10: *1 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream,
client: 172.25.0.1, server: impressive.local, request: "GET /api/index.php HTTP/1.1", upstream: "fastcgi://172.25.0.2:9000", host: "127.0.0.1:8080"
web_1  | 172.25.0.1 - - [13/Jan/2019:23:22:57 +0000] "GET /api/index.php HTTP/1.1" 404 27 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" "-"

我已經搜尋了幾個小時,在 Stack Exchange 上查看了多個其他答案。我似乎無法弄清楚是什麼原因造成的。我使用碼頭工人。下面是我的docker-compose.yml

version: '3'
services:
 web:
   image: nginx:alpine
   volumes:
     - ./web:/usr/share/nginx/html
     - ./conf/impressive.template:/etc/nginx/conf.d/default.conf
   ports:
     - "8080:80"
   links:
     - php

 php:
   image: php:7.3.1-fpm-alpine
   volumes:
     - ./web:/usr/share/nginx/html

/usr/share/nginx/html結構如下:

- api
   index.php
- public
   index.html
   something.html
   ...

api是 JSON API,public是靜態站點。

我希望任何api/*呼叫請求api/index.php和其他任何請求都可以通過/usr/share/nginx/html/public.

我終於解決了!

事實證明,根位置必須與 php-fpm 容器上文件的位置相匹配,因為這是通過以下方式過去的:

fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name

我不需要指定該行,因為它包含在:include fastcgi.conf;.

我不確定這是否是最優雅的解決方案:

upstream php {
 server php:9000;
}

server {
 listen 80 default_server;
 server_name _;
 index index.html index.php;
 root /usr/share/nginx/html/public;

 location /api {
   root /usr/share/nginx/html;
   try_files $uri /api/index.php$is_args$args;

   location ~ \.php$ {
     fastcgi_pass php;
     fastcgi_split_path_info ^(.+\.php)(/.*)$;
     include fastcgi.conf;
     internal;
   }
 }
}

引用自:https://serverfault.com/questions/948898