【原创】php-fpm + Nginx 配置方法

概要

1、简介

在处理使用 php 编写的 web 程序的时候,需要一个 php-fpm 服务在后台来处理 php 的代码运行。

而一般 php-fpm 都会与 web 服务器结合来使用,web 服务器专门用于接收用户的 FastCGI 请求,而 php-fpm 则专门用于处理 php 相关的业务逻辑。

本文总结使用 nginx 作为 web 服务器与 php-fpm 配合时需要的配置

2、环境信息

  • Ubuntu 18.04

  • nginx 1.14.0

  • php-fpm 7.2

正文

1、php-fpm 的 listen 配置

php-fpm 配置文件位于 /etc/php/7.2/fpm/pool.d/www.conf,php-fpm.sock 是 php-fpm 默认使用的 listen 方式,如下所示:

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific IPv4 address on
;                            a specific port;
;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all addresses
;                            (IPv6 and IPv4-mapped) on a specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = /run/php/php7.2-fpm.sock

可以看到文件中写到的有四种设置方法。ipv4:port,ipv6:port,port,/path/to/unix/socket。

(1) 通过 php-fpm.sock

php-fpm 配置是使用监听 unix socket 的方式来服务 php 处理程序,/etc/php/7.2/fpm/pool.d/www.conf 中的配置如下:

listen = /run/php/php7.2-fpm.sock

与此对应的 nginx 配置如下

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
location ~ \.php$ {
    fastcgi_pass   unix:/run/php/php7.2-fpm.sock;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
}

注:使用 socket 配置方式,php-fpm 的 listen.owner 和 nginx 的 user 必须相同。默认情况下相同的

/etc/php/7.2/fpm/pool.d/www.conf 中的 listen.owner 设置如下:

; Set permissions for unix socket, if one is used. In Linux, read/write
; permissions must be set in order to allow connections from a web server. Many
; BSD-derived systems allow connections regardless of permissions.
; Default Values: user and group are set as the running user
;                 mode is set to 0660
listen.owner = www-data
listen.group = www-data
;listen.mode = 0660

/etc/nginx/nginx.conf 中的 user 配置如下:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

默认情况下 php-fpm 与 nginx 的用户都是 www-data,所以可以不用改。另外,网站的资源目录比如 /data/www/website website 的目录不必是 www-data

(2) 通过 ipv4:port

php-fpm 程序可以在后台监听一个端口,其他程序可以访问该端口处理 FastCGI 请求。

listen = 127.0.0.1:9000

与此对应的 nginx 配置如下

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
location ~ \.php$ {
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
}

推荐使用这种方法 进行配置。另外两种不常使用,不作介绍。

You may also like...

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注