Nginx服務器proxy_cache 反向代理緩存設置
nginx 反代要緩存後端發過來的數據,並gzip保存,需要設置2個地方
gzip_http_version 1.0; proxy_set_header Accept-Encoding 'gzip';
如果 gzip_http_version 1.1 則不會壓縮
為了讓前端保存的緩存不會因為後端程序的小改動而頻繁更新,就用到了 ssi
要詳細說的話,會很長,只記要點
1. 緩存 gzip 與 ssi 不能兼得,可惜
2. 實例代碼:
後端程序輸出的頁面裡包含<!--#include virtual="/ssi/test.html"-->
前端如果不開 ssi,上面這句就是 html 注釋
然後在前端 /ssi/ 目錄裡放 test.html 文件
最後,/ssi/test.html 文件裡還可以再 include 動態文件
<!--#include virtual="/ssi/test.php"-->
3. 放點配置文件
# backend
server {
listen 8888;
server_name backend;
root /jasson/www/test_back.com;
include server.conf;
location / {
try_files $uri $uri/ /index.php;
}
}
# proxy & upstream setting
proxy_temp_path /jasson/www/proxy/temp;
proxy_cache_path /jasson/www/proxy/main levels=2 keys_zone=main:10m inactive=10d max_size=100m;
proxy_cache_path /jasson/www/proxy/21andy levels=2 keys_zone=main:10m inactive=10d max_size=100m;
upstream backend {
server 127.0.0.1:8888 weight=8 max_fails=2 fail_timeout=20s;
server 127.0.0.1:9999 weight=2 max_fails=2 fail_timeout=20s;
}
proxy_next_upstream http_502 http_503 http_504 error timeout invalid_header;
# frontend
server {
listen 80;
root /jasson/www/test.com;
server_name www.test.com test.com *.test.com;
if ($host != 'www.test.com') {
rewrite ^(.*)$ http://www.test.com$1 permanent;
}
index index.html index.php;
ssi on; # outside location for global
# cache uri begin with /21andy/
location ~* ^/21andy/ {
proxy_cache 21andy;
proxy_cache_valid 200 301 302 30d;
proxy_cache_valid any 3m;
proxy_pass http://backend;
}
# if file or directory EXISTS in frontend then output it directly
# else get from backend and cache it to main
try_files $uri $uri/ @cache;
location @cache {
proxy_cache main;
proxy_cache_valid 200 301 302 30d;
proxy_cache_valid any 3m;
proxy_pass http://backend;
}
# cache homepage
location =/ {
proxy_cache main;
proxy_cache_valid 200 1h;
proxy_pass http://backend;
}
# for SSI to be include php file
location ~* \.php$ {
try_files $uri =404;
fastcgi_index index.php;
fastcgi_pass unix:/tmp/php-cgi.sock;
include fastcgi_params;
}
}
*