在LNMP(Linux, Nginx, MySQL, PHP)環境中實現動靜分離,主要是通過Nginx來處理靜態資源,而將動態請求轉發給PHP處理。以下是實現動靜分離的步驟:
首先,確保你已經安裝了Nginx。如果還沒有安裝,可以使用以下命令進行安裝:
# 在CentOS上安裝Nginx
sudo yum install epel-release
sudo yum install nginx
sudo systemctl start nginx
sudo systemctl enable nginx
在Nginx的配置文件中,通常位于/etc/nginx/nginx.conf
或/etc/nginx/conf.d/
目錄下的某個文件,你需要配置靜態資源的處理。例如:
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html index.htm;
location /static/ {
alias /var/www/html/static/;
}
location / {
try_files $uri $uri/ /index.php?$query_string;
}
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;
}
}
在這個配置中,所有對/static/
路徑下的靜態資源請求將由Nginx直接處理,而其他請求將被轉發到PHP處理。
確保PHP-FPM正在運行,并且Nginx可以與之通信。通常,PHP-FPM的配置文件位于/etc/php-fpm.d/www.conf
或/etc/php-fpm.conf
。確保listen
指令設置為127.0.0.1:9000
或通過UNIX套接字與Nginx通信。
# 編輯PHP-FPM配置文件
sudo vim /etc/php-fpm.d/www.conf
# 確保以下配置
listen = 127.0.0.1:9000
listen.allowed_clients = 127.0.0.1
然后重啟PHP-FPM服務:
sudo systemctl restart php-fpm
將所有靜態資源(如CSS、JavaScript、圖片等)放在Nginx配置中指定的靜態資源目錄下,例如/var/www/html/static/
。
對于動態內容,如PHP腳本,將它們放在Nginx配置中location ~ \.php$
塊指定的目錄下,例如/var/www/html/
。
啟動Nginx和PHP-FPM服務后,使用瀏覽器訪問你的網站,確保靜態資源能夠被正確加載,動態內容也能夠通過PHP處理并返回。
通過以上步驟,你就可以在LNMP環境中實現動靜分離,提高網站的性能和可維護性。