溫馨提示×

Nginx 在 CentOS 上如何配置緩存以提高訪問速度

小樊
110
2025-02-08 12:48:05
欄目: 智能運維

在 CentOS 上配置 Nginx 緩存,可以通過以下步驟實現:

  1. 安裝 Nginx 和必要的依賴包:
sudo yum install epel-release
sudo yum install nginx
sudo yum install nginx-mod-http-cache
  1. 創建一個新的 Nginx 配置文件,例如 /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,并設置了緩存的級別、鍵區域、最大大小、不活躍時間等參數。我們還為不同類型的響應設置了不同的緩存有效期。

  1. 在 Nginx 主配置文件 /etc/nginx/nginx.conf 中,引入剛剛創建的緩存配置文件:
http {
    ...
    include /etc/nginx/conf.d/cache.conf;
    ...
}
  1. 重啟 Nginx 以應用新的配置:
sudo systemctl restart nginx

現在,Nginx 應該已經配置好了緩存功能,可以顯著提高訪問速度。請注意,這個示例僅適用于單個服務器,如果你有一個負載均衡器或者多個服務器,你可能需要根據需要進行更復雜的配置。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女