理解 Nginx 下的 fastcgi.conf 文件,nginxfastcgi.conf


最近用 docker 来搭建 nginx + php-fpm 服务器,参考网上的教程后发现了一个不太明白的地方。Docker-compose.yml 文件如下:

version: '3'

services:
    openresty:
        image: openresty/openresty:alpine
        network_mode: "host"
        volumes:
            - ./:/home
        command: openresty -p /home -c conf/nginx.conf -g "daemon off;"
        restart: always

    php73-fpm:
        image: php:7.3-rc-fpm-alpine
        network_mode: "host"
        volumes:
            - ./:/home
        restart: always

疑惑点:php73-fpm 容器下必须挂载 openresty 挂载过的文件卷?

带着疑问,在 google 上找到了答案。

Nginx 与 php-fpm 通信过程是通过 nginx 的 fastcgi 模块来处理的,即 fastcgi 模块将来自客户端的关于 php 文件的请求转发给 php-fpm 来处理。既然是转发请求,那么必须要遵循一定的协议,也就是 fastcgi.conf 所规定的协议了。

nginx.conf 中配置处理 php 文件的 location 规则如下:

server {
    listen 80;

    location ~ \.php$ {
        root /home/php;
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi.conf;
    }
}

fastcgi.conf 文件内容如下:


fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REQUEST_SCHEME     $scheme;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

其中,fastcgi_param指令指定放置PHP动态程序的主目录,也就是$fastcgi_script_name前面指定的路径,此处就是 /home/php。也就是说客户端请求 /home/php/xxx.php 文件, nginx 不能解析该文件,于是按照 fastcgi.conf 规定的规则将该请求转发给 php-fpm,其中规则指明了 php-fpm 到哪里去寻找 php 文件!

再回到前面的那个 docker 疑惑点,也就能明白为何要在 php-fpm 容器里挂载文件卷了,不然 php-fpm 容器找不到客户端要请求的 php 文件。

 

参考博客:

1. Dockerise your PHP application with Nginx and PHP7-FPM

2. Nginx+Php-fpm运行原理详解

3. FastCGI模块(FastCGI)

4. PHP-FastCGI详解

5. 深入理解Zend SAPIs(Zend SAPI Internals)

相关内容

    暂无相关文章