Home > Software design >  Why nginx ignores root and location directives?
Why nginx ignores root and location directives?

Time:10-24

I'm running Nginx as a service in docker-compose, with a volume mounted at /app inside the container.

I just copied the whole project structure from Linux to MacOS where it worked fine.

Here is my docker-compose.yml:

version: '3'
services:
    web:
        image: nginx:latest
        ports:
            - "80:80"
        volumes:
            - ./docker/nginx/nginx.conf:/etc/nginx/conf.d/nginx.conf
            - ./app:/app

    sass:
        image: larryprice/sass
        volumes:
            - ./app/public/assets:/src

    php:
        build:
            context: .
            dockerfile: ./docker/php/PHP.Dockerfile
        volumes:
            - ./app:/app

I have a simple configuration for a PHP app, but the root directive inside location seems to be ignored. I can't understand why.

This single configuration file in conf.d directory:

server {
    listen 80 default_server;
    root /app/public;

    index index.php index.html index.htm;

    location ~ \.php$ {
        fastcgi_pass php:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;     
    }
}

When trying to access http://localhost/index.php it fails with

172.19.0.1 - - [16/Oct/2021:11:22:28  0000] "GET /index.php HTTP/1.1" 404 555 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36" "-"
2021/10/16 11:22:28 [error] 26#26: *1 open() "/usr/share/nginx/html/index.php" failed (2: No such file or directory), client: 172.19.0.1, server: localhost, request: "GET /index.php HTTP/1.1", host: "localhost"

So, it defaults to looking in /usr/share/nginx/html/, but there is matching location for a uri.

Can anyone explain this? Many thanks!

CodePudding user response:

Settings in fastcgi_params may overwrite your SCRIPT_FILENAME param, you could try to move fastcgi_param SCRIPT_FILENAME after include fastcgi_params

server {
    listen 80 default_server;
    root /app/public;

    index index.php index.html index.htm;

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

CodePudding user response:

The project structure is from this resource: https://www.sitepoint.com/docker-php-development-environment/

Instead of just copying project structure from Linux (as I mentioned in a question) I sequentially followed this tutorial manually adding those directives and surprisingly it started to work fine.

  • Related