在現代Web開發中,PHP與Nginx的結合日益流行,能夠打造高性能且穩定的服務器環境。本文將帶你一步步完成在CentOS系統上安裝PHP與Nginx的過程,助你快速搭建靈活的Web服務。
安裝前請確保系統已升級至最新版本,運行以下命令完成更新:
<span class="fun">sudo yum update</span>
為便於安裝最新版本的PHP,需要先添加EPEL和Remi軟件源:
sudo yum install epel-release -y
sudo yum install https://rpms.remirepo.net/enterprise/remi-release-7.rpm -y
執行下列命令啟用PHP 8.1版本倉庫,當然你也可以根據需求啟用其他版本:
<span class="fun">sudo yum-config-manager --enable remi-php81</span>
接下來安裝PHP以及常見的擴展包,滿足大部分項目需求:
<span class="fun">sudo yum install php php-cli php-fpm php-mysqlnd php-xml php-mbstring -y</span>
安裝完畢後,需要編輯PHP-FPM配置文件,確保服務使用nginx用戶運行:
<span class="fun">sudo vi /etc/php-fpm.d/www.conf</span>
將以下配置修改為:
user = nginx
group = nginx
通過yum安裝Nginx:
<span class="fun">sudo yum install nginx -y</span>
sudo systemctl start nginx
sudo systemctl enable nginx
創建或編輯Nginx配置文件,加入對PHP的支持:
<span class="fun">sudo vi /etc/nginx/conf.d/default.conf</span>
添加以下內容:
server {
listen 80;
server_name your_domain.com; # 替換為你的域名或IP地址
root /usr/share/nginx/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
sudo systemctl start php-fpm
sudo systemctl enable php-fpm
創建一個簡單的PHP測試文件以驗證配置是否成功:
<span class="fun">echo "<?php phpinfo(); ?>" | sudo tee /usr/share/nginx/html/info.php</span>
在瀏覽器中訪問http://your_domain.com/info.php ,如果看到PHP信息頁面,說明PHP和Nginx已成功搭建。
按照以上步驟,你已經在CentOS系統上順利安裝並配置了PHP和Nginx,為Web開發環境打下堅實基礎。希望本指南能幫助你快速掌握相關技能。