在Nginx中配置緩存可以顯著提高網站的性能和響應速度。以下是一個基本的Nginx緩存配置示例:
安裝Nginx和相關模塊:
確保你已經安裝了Nginx,并且啟用了必要的模塊,如ngx_cache
和ngx_cache_purge
。
配置緩存路徑:
在Nginx配置文件中(通常是/etc/nginx/nginx.conf
或/etc/nginx/conf.d/default.conf
),添加一個緩存路徑:
http {
# 緩存路徑
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;
server {
listen 80;
server_name example.com;
location / {
# 啟用緩存
proxy_cache my_cache;
proxy_pass http://backend_server;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
add_header X-Proxy-Cache $upstream_cache_status;
}
# 清除緩存
location ~ /purge(/.*) {
allow 127.0.0.1; # 允許本地訪問
deny all; # 拒絕其他所有IP
proxy_cache_purge my_cache $scheme://$host$request_uri;
}
}
}
解釋配置:
proxy_cache_path
:定義緩存路徑和相關參數。
/var/cache/nginx
:緩存文件的存儲路徑。levels=1:2
:緩存目錄的層級結構。keys_zone=my_cache:10m
:定義緩存區域,名稱為my_cache
,大小為10MB。max_size=1g
:緩存的最大總大小為1GB。inactive=60m
:緩存文件在未被訪問60分鐘后失效。use_temp_path=off
:禁用臨時文件路徑。proxy_cache
:啟用緩存,并指定緩存區域。proxy_pass
:指定后端服務器地址。proxy_cache_valid
:設置不同HTTP狀態碼的緩存時間。add_header X-Proxy-Cache $upstream_cache_status
:添加響應頭,顯示緩存狀態。location ~ /purge(/.*)
:定義清除緩存的location塊。
allow 127.0.0.1
:允許本地IP訪問清除緩存接口。deny all
:拒絕其他所有IP訪問清除緩存接口。proxy_cache_purge my_cache $scheme://$host$request_uri
:清除指定URL的緩存。重啟Nginx: 保存配置文件后,重啟Nginx以應用更改:
sudo systemctl restart nginx
通過以上步驟,你可以在Nginx中配置基本的緩存功能。根據實際需求,你可以進一步調整緩存參數和策略,以優化性能。