利用Nginx實現動靜分離是一種常見的優化手段,可以提高網站的性能和響應速度。動靜分離的基本思想是將動態內容(如PHP、ASP.NET等)和靜態內容(如HTML、CSS、JavaScript、圖片等)分別處理,以減輕應用服務器的負擔。以下是實現動靜分離的步驟:
首先,確保你已經安裝了Nginx。如果還沒有安裝,可以參考官方文檔進行安裝。
在Nginx的配置文件中(通常是/etc/nginx/nginx.conf或/etc/nginx/sites-available/default),創建或修改一個服務器塊來處理靜態內容。
server {
listen 80;
server_name example.com;
# 靜態資源目錄
root /var/www/static;
location / {
try_files $uri $uri/ =404;
}
# 處理圖片、CSS、JS等靜態文件
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public";
}
}
在同一服務器塊中,添加一個location塊來處理動態內容,例如PHP請求。
# 處理PHP請求
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根據你的PHP版本調整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
如果你有多個應用服務器,可以使用Nginx作為反向代理來分發請求。
upstream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# 靜態資源目錄
root /var/www/static;
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public";
}
# 處理PHP請求
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根據你的PHP版本調整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
在修改配置文件后,使用以下命令測試配置是否正確:
sudo nginx -t
如果沒有錯誤,重啟Nginx以應用更改:
sudo systemctl restart nginx
訪問你的網站,確保靜態資源(如圖片、CSS、JS)直接從Nginx服務器提供,而動態內容(如PHP頁面)通過反向代理轉發到應用服務器。
通過以上步驟,你就可以利用Nginx實現動靜分離,提高網站的性能和響應速度。