【问题标题】:Docker - NGINX Container forward to PHP-FPM ContainerDocker - NGINX 容器转发到 PHP-FPM 容器
【发布时间】:2021-02-23 12:55:32
【问题描述】:

我在单独的容器中运行 NGINX、PHP-FPM 和 DB。

PHP-FPM 内部正在从我的本地机器上安装一个 Laravel 项目。

在访问 127.0.0.1:8000 时,我已成功将 PHP 请求转发到 PHP-FPM 容器(端口 9000)。不幸的是,带有资产扩展名(例如 .css、.js)的请求已遇到 403 禁止。

以下是我的 NGINX 配置脚本。

server {
    listen 80;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass fpm:9000;
        fastcgi_param SCRIPT_FILENAME /app/public$fastcgi_script_name;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~* \.(css|js|gif|ico|jpeg|jpg|png)$ {
        fastcgi_pass fpm:9000;
        fastcgi_param SCRIPT_FILENAME /app/public$fastcgi_script_name;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_index index.php;
        include fastcgi_params;
    }
}

app.css 文件的请求和响应标头。

不确定是否有人遇到过类似的问题并有解决方案?

【问题讨论】:

  • 您能否为任何 403 请求添加带有完整响应标头列表的屏幕截图?
  • @IvanShatsky 按要求添加。

标签: php laravel docker nginx


【解决方案1】:

您将所有内容转发到 PHP FPM,同时,默认情况下,在 PHP-FPM 进程配置文件中,它只允许提供 .php 文件。

你可以在php-fpm容器中签入/usr/local/etc/php-fpm.d/www.conf,然后搜索security.limit_extensions,你就会看到。

所以这里有 2 个解决方案

解决方案 1:将项目源映射到运行 Nginx 的容器中,如下所示:

# docker-compose.yml

webserver:
    image: nginx:1.17-alpine
    restart: unless-stopped
    ports:
      - "8000:80"
    volumes:
      - ./:/var/www/html

通过这样做,Nginx 可以轻松找到您的静态文件并提供服务。请注意,/var/www/html 是您在 Nginx 配置文件中定义的根项目路径。例如,Laravel 项目的 Nginx 配置文件通常如下所示:

server {
    listen 80;
    index index.php index.html;

    root /var/www/html/public;
    ...

解决方案 2:将.css, .js 添加到 PHP-FPM 进程配置文件,使用此解决方案,您将覆盖 PHP-FPM 配置文件并将静态文件添加到 PHP-FPM 允许的文件扩展名列表中。检查我的演示here。此解决方案不需要您将项目映射到 Nginx 容器中。但实际上它不适合像解决方案 1 那样的生产

【讨论】:

  • 为此工作的解决方案 :) 唯一的缺点是需要定义 Web 服务器所需的所有扩展。如果能自动转发content-type就更好了。
猜你喜欢
  • 2018-07-17
  • 2021-04-08
  • 2021-03-30
  • 2015-07-06
  • 2017-10-04
  • 2017-03-31
  • 1970-01-01
  • 2017-04-30
相关资源
最近更新 更多