在現代Web應用架構中,Linux、PHP-FPM(FastCGI Process Manager)和Nginx的搭配使用是非常常見的組合。這種組合能夠提供高性能、高可靠性和可擴展性。以下是如何在Linux系統上配置Nginx和PHP-FPM的步驟:
首先,你需要在你的Linux系統上安裝Nginx。以下是在基于Debian的系統(如Ubuntu)上的安裝命令:
sudo apt update
sudo apt install nginx
在基于Red Hat的系統(如CentOS)上的安裝命令:
sudo yum install epel-release
sudo yum install nginx
接下來,安裝PHP-FPM。以下是在基于Debian的系統上的安裝命令:
sudo apt install php-fpm
在基于Red Hat的系統上的安裝命令:
sudo yum install php-fpm
編輯PHP-FPM的配置文件,通常位于/etc/php/7.x/fpm/pool.d/www.conf
(其中7.x
是你的PHP版本)。確保以下配置項正確:
; 監聽的socket文件路徑
listen = /run/php/php7.x-fpm.sock
; 監聽的TCP端口(可選)
; listen = 127.0.0.1:9000
; 用戶和組
user = www-data
group = www-data
; PM模式(推薦使用dynamic)
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
編輯Nginx的默認站點配置文件,通常位于/etc/nginx/sites-available/default
。以下是一個基本的配置示例:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.x-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
啟動Nginx和PHP-FPM服務,并設置它們在系統啟動時自動啟動。
在基于Debian的系統上:
sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl start php7.x-fpm
sudo systemctl enable php7.x-fpm
在基于Red Hat的系統上:
sudo systemctl start nginx
sudo systemctl enable nginx
sudo systemctl start php-fpm
sudo systemctl enable php-fpm
最后,測試Nginx和PHP-FPM的配置是否正確。你可以通過訪問你的網站來檢查是否能夠正常顯示PHP頁面。
curl http://example.com
如果一切配置正確,你應該能夠看到PHP腳本的輸出。
通過以上步驟,你已經成功地在Linux系統上配置了Nginx和PHP-FPM。這種組合能夠提供高性能的Web服務,并且易于擴展和維護。