【问题标题】:Why nginx ignores root and location directives?为什么 nginx 忽略 root 和 location 指令?
【发布时间】:2021-12-04 06:51:38
【问题描述】:

我在 docker-compose 中将 Nginx 作为服务运行,并在容器内的 /app 处安装了一个卷。

我刚刚将整个项目结构从 Linux 复制到 MacOS,它运行良好。

这是我的 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

我有一个 PHP 应用程序的简单配置,但位置内的根指令似乎被忽略了。我不明白为什么。

conf.d目录下的这个单一配置文件:

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;     
    }
}

当尝试访问http://localhost/index.php 时失败

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"

因此,它默认查找 /usr/share/nginx/html/,但有匹配的 location 用于 uri。

谁能解释一下? 非常感谢!

【问题讨论】:

  • 这不是处理请求的server 块。 /etc/nginx/nginx.conf 文件中必须定义另一个 server 块。
  • @RichardSmith,我的/etc/nginx/nginx.conf 文件中没有server 块,但我在这个文件的http 块中有include /etc/nginx/conf.d/*.conf;
  • 你能把 nginx.conf 文件挂载到/etc/nginx/nginx.conf 吗?这可能是因为主文件已经在那里配置了根目录,所以你需要像我建议的那样覆盖它或替换它

标签: php docker nginx docker-compose


【解决方案1】:

项目结构来源于此资源:https://www.sitepoint.com/docker-php-development-environment/

我不只是从 Linux 复制项目结构(正如我在一个问题中提到的),我依次按照本教程手动添加了这些指令,令人惊讶的是它开始正常工作。

【讨论】:

    【解决方案2】:

    fastcgi_params 中的设置可能会覆盖您的SCRIPT_FILENAME 参数,您可以尝试在include fastcgi_params 之后移动fastcgi_param SCRIPT_FILENAME

    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;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2011-08-23
      • 2015-09-04
      • 1970-01-01
      • 2012-09-06
      • 2014-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多