Ubuntu配置Nginx+PHP

2021-02-19

最近折腾PHP,经过了一番查资料、debug的艰辛过程,总算配置好了Nginx和PHP。总结一下经验,供自己日后回顾以及他人借鉴经验。

环境:Ubuntu 20.04.2

过程:

1. 安装 Nginx:sudo apt-get install nginx

‍      验证Nginx安装成功:用浏览器打开对应的IP。若出现下图,Nginx服务安装成功。

2. 安装php-fpm:sudo apt-get install php-fpm 

3. 对Nginx进行配置:

‍    3.1 Nginx的配置文件为nginx.conf,我安装时,它位于/etc/nginx/nginx.conf。

‍    3.2 对Nginx.conf进行修改:vim /etc/nginx/nginx.conf

‍        3.2.1 在http{}中新增如下内容,以将处理php的请求传递给php-fpm

‍                server {

‍                       listen 443 ssl;# 443https的端口,如果你用的是http就用‘80’代替‘443 ssl’

‍                       server_name webofhu.com; #此处用你的域名代替webofhu.com

‍                       root /a/b/c;#此处用网站的位置代替/a/b/c

‍                       index index.php index.html index.htm

‍ 

‍                       …其他内容


‍                       location ~ \.php$ {

‍                           include fastcgi.conf;

‍                           fastcgi_pass   127.0.0.1:9000;

‍                           fastcgi_index  index.php;

‍                           fastcgi_split_path_info ^(.+\.php)(/.+)$;

‍                           fastcgi_param PATH_INFO $fastcgi_path_info;

‍                           fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;

‍                           fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

‍                       }

‍                   }

‍        3.2.2 检查nginx.conf是否正常:

‍                 # 下面执行的nginx位于/usr/sbin,可以根据自己文件的路径进行调整

‍                 cd /usr/sbin

‍                    ./nginx -t

‍                若出现以下内容则表明nginx.conf配置正确

‍                nginx: the configuration file /etc/nginx/nginx.conf syntax is ok

‍                   nginx: configuration file /etc/nginx/nginx.conf test is successful

4. 对php-fpm进行配置:

‍    4.1 修改www.conf文件:vim /etc/php/7.4/fpm/pool.d/www.conf # 根据自己www.conf文件位置进行调整

‍    4.2 查找’Default Value: any’的位置,将下面的‘listen’修改为以下内容:

‍            listen = 127.0.0.1:9000

‍            listen.allowed_clients = 127.0.0.1

‍    4.3 重启php-fpm:

‍            systemctl stop php7.4-fpm.service

‍               systemctl stop php7.4-fpm.service

5. 验证配置是否成功:

‍    5.1 在index.html位置新建test.php文件:touch test.php

‍    5.2 在test.php文件中新增如下内容:

‍            <?php

‍            phpinfo();

‍            ?>

‍    5.3 重启nginx服务:service nginx restart

‍    5.4 访问域名.com/test.php,若出现以下内容则说明配置正确:

‍ 

表明Nginx服务安装成功。