Home > OS >  FastCGI PHP File not found only when FETCH is used
FastCGI PHP File not found only when FETCH is used

Time:07-27

I'm doing a little project to learn Docker - NextJS PHP backend with Nginx.

Now I got to a stage when I can say it works somehow. When reaching the API via browser adress bar, it gives me the error page - That's right. Nginx not complaining.

BUT when I try to FETCH it, it gives me file not found from the PHP-FPM container and the Nginx complains FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream

The site config is this

upstream next_app {
  # NextJS running app port
  server nextapp:3000;
}

upstream php_fpm {
  # PHP FPM server URI and port
  server phpapp:9000;
}

server {
  listen 80 default_server;

  server_name _;

  server_tokens off;

  error_log /var/log/nginx/error.log;
  access_log /var/log/nginx/access.log;

  location ~ ^/api {
      root /var/www;
      try_files /www/index.php =404;

      include fastcgi_params;
      fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

      fastcgi_pass php_fpm;
  }

  # proxy pass for NodeJS app
  proxy_http_version 1.1;

  proxy_set_header Host                $http_host;
  proxy_set_header X-Real-IP           $remote_addr;
  proxy_set_header X-Forwarded-For     $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto   $scheme;
  proxy_set_header Host                $host;
  proxy_cache_bypass $http_upgrade;

  location / {
    proxy_pass http://next_app;
  }
}

The basic idea was to use PHP api on any request with query starting with /api.

I have a little suspicion on the Next app serving me different Fetch, but I didn't found anything to help it

Any idea how to make it work? Thanks

CodePudding user response:

So, solved now, thanks to @ad7six comments I realized the problem is more accurately described by "How the hell can I print out a Nginx variable when everything around fails?"

There's two ways - use return and it comes with the response body or add_header with the always attribute.

  add_header X-cgiscript 42 always;

  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME /var/www/www/index.php;

  fastcgi_pass php_fpm;

So now the FPM only executes the index.php of the whole app. Thanks

  • Related