温馨提示×

Ubuntu中php-fpm与Nginx如何配合使用

小樊
38
2025-02-21 19:18:00
栏目: 编程语言
PHP开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Ubuntu系统中,PHP-FPM(FastCGI Process Manager)和Nginx可以很好地配合使用,以提供高效的PHP网站和应用程序服务。以下是配置Nginx与PHP-FPM配合使用的步骤:

1. 安装Nginx和PHP-FPM

首先,确保你的系统是最新的:

sudo apt update
sudo apt upgrade

然后安装Nginx和PHP-FPM:

sudo apt install nginx php-fpm

2. 配置PHP-FPM

PHP-FPM的配置文件通常位于 /etc/php/7.x/fpm/pool.d/www.conf(其中 7.x 是你的PHP版本)。你可以根据需要进行一些基本配置,例如监听地址和端口:

; listen = /run/php/php7.x-fpm.sock ; for a unix socket
listen = 127.0.0.1:9000 ; for a tcp socket

确保PHP-FPM服务正在运行并设置为开机自启动:

sudo systemctl start php7.x-fpm
sudo systemctl enable php7.x-fpm

3. 配置Nginx

编辑Nginx的默认站点配置文件,通常位于 /etc/nginx/sites-available/default

sudo nano /etc/nginx/sites-available/default

server 块中,添加或修改以下内容:

server {
    listen 80;
    server_name your_domain.com www.your_domain.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
        # 或者使用tcp socket
        # fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }
}

确保将 your_domain.com 替换为你的实际域名,并将 /var/www/html 替换为你的网站根目录。

4. 检查Nginx配置并重启

在保存并退出编辑器后,检查Nginx配置文件是否有语法错误:

sudo nginx -t

如果没有错误,重启Nginx服务以应用更改:

sudo systemctl restart nginx

5. 测试配置

现在,你应该能够通过浏览器访问你的域名,并看到PHP页面正常显示。你可以创建一个简单的PHP文件(例如 info.php)来测试PHP是否正常工作:

<?php
phpinfo();
?>

将这个文件放在你的网站根目录下,然后访问 http://your_domain.com/info.php,你应该能看到PHP的信息页面。

通过以上步骤,你已经成功配置了Nginx与PHP-FPM的配合使用。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:ubuntu php-fpm如何与Nginx配合使用

0