确保你使用的是 CentOS 7 或 CentOS 8 系统,并具有 root 权限或 sudo 权限。
# 添加 EPEL 仓库
sudo yum install epel-release
# 安装 Nginx
sudo yum install nginx
# 启动 Nginx 并设置开机启动
sudo systemctl start nginx
sudo systemctl enable nginx
# 安装 Nginx
sudo dnf install nginx
# 启动 Nginx 并设置开机启动
sudo systemctl start nginx
sudo systemctl enable nginx
# CentOS 7
sudo yum install php php-fpm php-mysqlnd php-opcache php-gd php-xml php-mbstring
# CentOS 8
sudo dnf install php php-fpm php-mysqlnd php-opcache php-gd php-xml php-mbstring
编辑 /etc/php-fpm.d/www.conf
文件:
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
sudo systemctl start php-fpm
sudo systemctl enable php-fpm
编辑默认的 Nginx 配置文件:
sudo vi /etc/nginx/nginx.conf
在 http
块中添加以下内容(如果不存在):
server_names_hash_bucket_size 64;
然后编辑默认的 server 配置或创建一个新的:
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/ =404;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
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 /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/ =404;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
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
在网站目录中创建 PHP 测试文件:
sudo vi /var/www/example.com/public_html/info.php
添加以下内容:
<?php phpinfo(); ?>
然后在浏览器中访问 http://example.com/info.php
(确保已配置本地 hosts 文件或 DNS 解析)。
# 开放 HTTP 和 HTTPS 端口
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=public --add-service=https
sudo firewall-cmd --reload
如果启用了 SELinux,可能需要执行以下命令:
sudo chcon -Rt httpd_sys_content_t /var/www/example.com/public_html
sudo setsebool -P httpd_can_network_connect 1
这样就完成了在 CentOS 上部署 Nginx、PHP 和虚拟主机的全部过程。