在 CentOS 上配置 Nginx 緩存,可以通過以下步驟實現:
sudo yum install epel-release
sudo yum install nginx
sudo yum install nginx-mod-http-cache
/etc/nginx/conf.d/cache.conf
,并添加以下內容:http {
proxy_cache_path /tmp/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_pass http://backend_server;
proxy_cache my_cache;
proxy_cache_valid 200 302 30m;
proxy_cache_valid 404 1m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
proxy_cache_bypass $http_cache_control;
proxy_cache_key $scheme$host$request_uri$is_args$args;
}
}
}
在這個配置文件中,我們定義了一個緩存路徑 /tmp/nginx
,并設置了緩存的級別、鍵區域、最大大小、不活躍時間等參數。我們還為不同類型的響應設置了不同的緩存有效期。
/etc/nginx/nginx.conf
中,引入剛剛創建的緩存配置文件:http {
...
include /etc/nginx/conf.d/cache.conf;
...
}
sudo systemctl restart nginx
現在,Nginx 應該已經配置好了緩存功能,可以顯著提高訪問速度。請注意,這個示例僅適用于單個服務器,如果你有一個負載均衡器或者多個服務器,你可能需要根據需要進行更復雜的配置。