首先确保你的CentOS系统是最新的:
sudo yum update -y
sudo yum install epel-release -y
sudo yum install nginx -y
启动Nginx并设置开机自启:
sudo systemctl start nginx
sudo systemctl enable nginx
CentOS 7默认仓库中的PHP版本可能较旧,建议安装较新版本:
sudo yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm
sudo yum-config-manager --enable remi-php74 # 可根据需要选择其他版本如php80
sudo yum install php php-fpm php-mysqlnd php-opcache php-gd php-xml php-mbstring -y
启动PHP-FPM并设置开机自启:
sudo systemctl start php-fpm
sudo systemctl enable php-fpm
编辑PHP-FPM配置文件:
sudo vi /etc/php-fpm.d/www.conf
找到并修改以下行:
user = nginx
group = nginx
listen = /var/run/php-fpm/php-fpm.sock
listen.owner = nginx
listen.group = nginx
重启PHP-FPM:
sudo systemctl restart php-fpm
编辑Nginx默认配置文件:
sudo vi /etc/nginx/nginx.conf
在http
块内确保包含以下内容:
server_names_hash_bucket_size 64;
然后编辑默认站点配置:
sudo vi /etc/nginx/conf.d/default.conf
修改为类似以下内容:
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
测试Nginx配置并重启:
sudo nginx -t
sudo systemctl restart nginx
sudo mkdir -p /var/www/example.com/public_html
sudo chown -R nginx:nginx /var/www/example.com/public_html
sudo chmod -R 755 /var/www
sudo vi /var/www/example.com/public_html/index.php
内容:
<?php phpinfo(); ?>
sudo vi /etc/nginx/conf.d/example.com.conf
内容:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/public_html;
index index.php index.html index.htm;
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
location / {
try_files $uri $uri/ /index.php?$args;
}
location ~ \.php$ {
try_files $uri =404;
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
sudo nginx -t
sudo systemctl restart nginx
如果你没有域名,可以修改本地hosts文件测试:
sudo vi /etc/hosts
添加:
127.0.0.1 example.com www.example.com
如果启用了防火墙,需要允许HTTP流量:
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
访问 http://example.com
或 http://your-server-ip
,你应该能看到PHP信息页面。
502 Bad Gateway错误:
systemctl status php-fpm
403 Forbidden错误:
sudo setenforce 0
(临时禁用)或配置正确的SELinux上下文PHP文件被下载而不是执行:
按照以上步骤,你应该能够在CentOS上成功部署Nginx、PHP并配置虚拟主机。