Ubuntu PHP-FPM(FastCGI Process Manager)与Nginx协同工作的关键在于正确配置Nginx以将PHP请求传递给PHP-FPM。以下是详细的步骤和解释:
首先,确保你已经安装了Nginx和PHP-FPM。你可以使用以下命令来安装它们:
sudo apt update
sudo apt install nginx php-fpm
PHP-FPM的配置文件通常位于 /etc/php/7.x/fpm/pool.d/www.conf(其中 7.x 是你的PHP版本)。你需要确保以下配置项正确:
; 监听的地址和端口
listen = /run/php/php7.x-fpm.sock ; 使用Unix socket
; 或者
; listen = 127.0.0.1:9000 ; 使用TCP/IP
; 是否允许外部连接
listen.allowed_clients = 127.0.0.1
; 用户和组
user = www-data
group = www-data
编辑Nginx的默认站点配置文件 /etc/nginx/sites-available/default 或创建一个新的配置文件。以下是一个示例配置:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.x-fpm.sock; ; 使用Unix socket
; 或者
; fastcgi_pass 127.0.0.1:9000; ; 使用TCP/IP
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
启动PHP-FPM和Nginx服务,并设置它们在系统启动时自动运行:
sudo systemctl start php7.x-fpm
sudo systemctl enable php7.x-fpm
sudo systemctl start nginx
sudo systemctl enable nginx
确保Nginx和PHP-FPM都在运行,并且配置文件没有语法错误:
sudo nginx -t
如果没有错误,重新加载Nginx以应用更改:
sudo systemctl reload nginx
创建一个简单的PHP文件(例如 /var/www/html/index.php)来测试配置:
<?php
phpinfo();
?>
访问 http://example.com,你应该能看到PHP信息页面,这表明Nginx正确地将PHP请求传递给了PHP-FPM。
通过以上步骤,你就可以成功地在Ubuntu上配置Nginx与PHP-FPM协同工作。