CentOS 7 PHP Nginx 部署指南

环境准备
在开始部署PHP和Nginx之前,我们需要确保以下环境已经准备就绪:
- 操作系统:CentOS 7
- 网络连接:确保网络畅通,能够访问互联网
- 软件包管理器:Yum
安装Nginx
安装Nginx
我们需要安装Nginx,使用以下命令安装:
sudo yum install nginx
启动Nginx
安装完成后,启动Nginx服务:
sudo systemctl start nginx
设置Nginx开机自启
为了在系统启动时自动启动Nginx,我们需要设置开机自启:
sudo systemctl enable nginx
检查Nginx状态
使用以下命令检查Nginx服务状态:
sudo systemctl status nginx
安装PHP
安装PHP
我们需要安装PHP,使用以下命令安装:

sudo yum install php php-fpm
启动PHP-FPM
安装完成后,启动PHP-FPM服务:
sudo systemctl start php-fpm
设置PHP-FPM开机自启
为了在系统启动时自动启动PHP-FPM,我们需要设置开机自启:
sudo systemctl enable php-fpm
检查PHP-FPM状态
使用以下命令检查PHP-FPM服务状态:
sudo systemctl status php-fpm
配置Nginx
编辑Nginx配置文件
使用以下命令编辑Nginx配置文件:
sudo nano /etc/nginx/nginx.conf
修改配置文件
在配置文件中找到以下部分:
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
location / {
index index.html index.htm index.php;
try_files $uri $uri/ /index.php?$query_string;
}
# location ~ \.php$ {
# include snippets/fastcgi-php.conf;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
# }
} 取消注释location ~ \.php$部分,并确保fastcgi_pass指向PHP-FPM监听的地址和端口(默认为0.0.1:9000)。
保存并退出编辑器
使用以下命令保存并退出编辑器:

Ctrl + X Y
重启Nginx以应用配置更改
使用以下命令重启Nginx:
sudo systemctl restart nginx
测试PHP和Nginx
创建测试文件
在Nginx的根目录下创建一个名为info.php的文件,并添加以下内容:
<?php phpinfo(); ?>
访问测试文件
在浏览器中访问http://localhost/info.php,如果一切配置正确,你应该能看到PHP的信息页面。
FAQs
问题1:为什么我的网站无法访问PHP文件?
解答:请检查以下方面:
- 确保Nginx和PHP-FPM服务已启动。
- 检查Nginx配置文件中的
location ~ \.php$部分是否正确配置。 - 确保PHP文件具有正确的文件权限,Nginx用户可以读取和执行。
- 检查PHP配置文件
/etc/php.ini中的allow_url_include是否设置为Off。
问题2:如何更改PHP-FPM的监听端口?
解答:编辑PHP-FPM配置文件/etc/php-fpm.d/www.conf,找到以下部分:
; listen = /var/run/php-fpm.sock listen = 127.0.0.1:9000
将listen行中的端口号更改为所需的端口号,然后重启PHP-FPM服务:
sudo systemctl restart php-fpm

