nginx的版本
./nginx -v
nginx version: nginx/1.9.15
需求
要求nginx缓存静态资源,如js、css、图片等,避免对静态资源的访问直接穿透到后端的j2ee应用侧,提高后端j2ee应用的运行效率。
配置方法
针对js、css、图片文件
分别增加缓存路径的指令,比如对于图片,增加如下的指令:
proxy_cache_path proxy_cache_image levels=1:2 keys_zone=cache_image:100m;
分别增加路径转发配置的指令,比如对于图片,增加如下的指令:
location ~ \.(gif|jpg|jpeg|png)$ {
proxy_cache cache_image;
proxy_cache_key $uri$is_args$args;
proxy_cache_valid 200 206 14d;
proxy_pass http://127.0.0.1:18080;
}
增加如下指令,在HTTP响应消息的头部中增加资源请求命中的标识。
add_header X-Cache $upstream_cache_status; # $upstream_cache_status表示资源缓存的状态,可选值有HIT MISS EXPIRED三种状态
使用浏览器调试面板中的网络视图,查看浏览器收到的响应消息的头部,如下所示
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/css
Date:Sat, 07 Jan 2017 12:00:37 GMT
ETag:W/"5576-1457782914000"
Last-Modified:Sat, 12 Mar 2016 11:41:54 GMT
Server:nginx
Transfer-Encoding:chunked
Vary:Accept-Encoding
X-Cache:HIT # 表明缓存命中
完整的样例配置
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
server_tokens off;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_buffers 128 32k;
gzip_comp_level 6;
gzip_http_version 1.1;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml application/xml application/json text/javascript application/javascript application/x-javascript;
charset utf-8;
proxy_cache_path proxy_cache_image levels=1:2 keys_zone=cache_image:100m;
proxy_cache_path proxy_cache_js levels=1:2 keys_zone=cache_js:100m;
proxy_cache_path proxy_cache_css levels=1:2 keys_zone=cache_css:100m;
server {
listen 8080;
server_name 192.168.0.107;
location ~ \.js {
proxy_cache cache_js;
proxy_cache_key $uri$is_args$args;
proxy_cache_valid 200 206 14d;
proxy_pass http://127.0.0.1:18080;
}
location ~ \.css {
proxy_cache cache_css;
proxy_cache_key $uri$is_args$args;
proxy_cache_valid 200 206 14d;
proxy_pass http://127.0.0.1:18080;
}
location ~ \.(gif|jpg|jpeg|png)$ {
proxy_cache cache_image;
proxy_cache_key $uri$is_args$args;
proxy_cache_valid 200 206 14d;
proxy_pass http://127.0.0.1:18080;
}
location ~ / {
index index.jsp;
proxy_pass http://127.0.0.1:18080;
proxy_set_header referer '';
include proxy.conf;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
}
}
对proxy_cache_key参数的简单说明
上述样例中,使用到了如下指令
proxy_cache_key $uri$is_args$args;
$uri,请求中的当前URI,例如/foo/bar.html。
$is_args,如果$args设置,值为”?”,否则为””。
$args,这个变量等于GET请求中的参数。例如,foo=123&bar=blahblah。
使用上述参数,可以有效完成对如下资源样式的区分
参考资料