使用PHP-FPM安装Ubuntu Server上的nginx

时间:2020-07-27 12:59:35  来源:igfitidea点击:

在本教程中,我们将学习如何在Ubuntu Server 16.04上安装nginx。
我们还将安装PHP编程语言,以从Ubuntu Nginx Web服务器提供动态内容。

使用apt get命令安装nginx

首先,更新APT源列表,然后使用apt-get命令安装ubuntu上的nginx。

打开Ubuntu终端并键入:

sudo apt-get update
sudo apt-get install nginx

运行systemctl命令以确保已正确安装nginx并运行。

systemctl status nginx

要检查我们安装的nginx版本,执行:

nginx -v

最后尝试使用Web浏览器访问Nginx Web服务器。
打开Ubuntu Server的Web浏览器和类型,IP地址或者域名。

我们应该看到默认的nginx欢迎页面,如上图片显示。

安装PHP FPM包

要使用nginx的服务器PHP,我们需要在Ubuntu服务器上安装PHP_FPM(FastCGI Process Manager)。

sudo apt-get install php7.0-fpm

配置PHP-FPM和NGINX

首先,打开/etc/php/7.0/fpm/php.ini文件,找到行; cgi.fix_pathinfo = 1.
然后,取消注释行(删除分号)并将值更改为0。

cgi.fix_pathinfo=0

接下来,我们需要配置nginx来使用PHP处理器。
打开默认站点的配置文件。

vim /etc/nginx/sites-available/default

使用“索引”找到行开始,并将index.php添加为第一个选项。

index index.php index.html index.htm index.nginx-debian.html;

然后,添加以下位置指令。

location ~ \.php${    
        include fastcgi_params;    
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;    
        fastcgi_param QUERY_STRING    $query_string;    
        fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
}

配置文件应类似于如下所示。

server {
        listen 80 default_server;
        listen [::]:80 default_server;
        root /var/www/html;
        # Add index.php to the list if you are using PHP
        index index.php index.html index.htm index.nginx-debian.html;
        server_name _;
        location/{
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/=404;
        }
        location ~ \.php${
                include fastcgi_params;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                fastcgi_param QUERY_STRING    $query_string;
                fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        }
}

使用SystemCtl命令保存配置文件,然后重新启动PHP7.0-FPM和NGINX服务。

systemctl restart php7.0-fpm.service
systemctl restart nginx.service

要测试PHP配置,请在DocumentRoot中创建索引.php文件。

vim /var/www/html/index.php

添加phpinfo()函数。

<?php phpinfo(); ?>

然后,打开Web浏览器并查看index.php文件。
在地址列类型中:

http://ip-address-of-server/index.php

我们应该看到包含有关Ubuntu Server上安装的PHP信息的网页。