Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Nginx 靜態資源壓縮、快取過期與動態頁面 Proxy Cache 完整配置

編輯:關於伺服器

一、靜態資源過期時間 (瀏覽器快取)

location ~* \.(ico|gif|bmp|jpg|jpeg|png|swf|js|css|mp3)$ {
    root /var/www/opkeep;
    expires 30d;  # 30 天強快取
}

二、Gzip 壓縮傳輸

gzip on;
gzip_min_length 1000;
gzip_buffers 4 8k;
gzip_types text/plain application/x-javascript text/css application/xml application/json;
# 建議加上 application/javascript text/javascript
gzip_vary on;  # 回應 Vary: Accept-Encoding

效果:文字類資源壓縮至原始 20-30%,大幅節省頻寬。

三、動態頁面 Proxy Cache (反向代理快取)

# http 區塊定義快取區域
proxy_cache_path /www/cache levels=1:2 keys_zone=Z:10m inactive=1m max_size=30g;

server {
    listen 80;
    server_name localhost;

    location / {
        root /www;
        proxy_cache Z;
        proxy_cache_valid 200 1m;  # 200 狀態快取 1 分鐘
        include proxy.conf;

        # 檔案不存在時反向代理至上游
        if (!-e $request_filename) {
            proxy_pass https://192.168.1.199:45815;
        }
    }

    # AJAX 等即時介面不快取
    location /ajax/ {
        include proxy.conf;
        if (!-e $request_filename) {
            proxy_pass https://192.168.1.199:45815;
        }
    }
}

四、proxy.conf 關鍵參數

proxy_redirect off;
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 Accept-Encoding "gzip";

client_max_body_size 100m;
client_body_buffer_size 256k;

proxy_connect_timeout 60;
proxy_send_timeout 60;
proxy_read_timeout 60;

proxy_buffer_size 512k;
proxy_buffers 8 512k;
proxy_busy_buffers_size 512k;
proxy_temp_file_write_size 512k;

關鍵參數解析

  • inactive=1m:快取項 **1 分鐘無存取** 則從快取區刪除 (非過期時間)。
  • proxy_cache_valid 200 1m:僅快取 200 狀態,**1 分鐘過期** 需回源驗證。
  • proxy_set_header Accept-Encoding "gzip":要求上游壓縮回應,節省頻寬。
  • proxy_buffer_size/buffers:記憶體緩衝區,**超過則寫入臨時檔** (proxy_temp_path),適當放大減少磁碟 IO。

HTML 動態快取補充

若需快取 HTML,取消註解 expires max; 並確保上游回應 Cache-Control 允許快取,或使用 proxy_cache_valid 200 302 10m; 等。

Copyright © Windows教程網 All Rights Reserved