Nginx 反向代理可以缓存 HTTP POST 请求页面吗?
2017-09-05 景峯
本文节选自《Netkiller Web 手札》 作者:netkiller 网站:http://www.netkiller.cn
答案是可以!
因为nginx 使用 url 作为缓存的key ( Nginx 将url地址 md5后作为缓存的 key ),所以默认情况下 Nginx 只能处理 HTTP GET 缓存。
对于 HTTP POST 请求,提交数据放在HTTP Head 头部提交到服务器的, 提交前后URL始终不变,Nginx 无法区分相同网址两次请求的内容有变化。
但是我们可以自定义 缓存 key 例如: "$request_uri|$request_body" 我们将请求地址加上post内容作为缓存的key,这样nginx 便可以区分每次提交后的页面变化。
$request_body 用于缓存的例子:
1proxy_cache_path /tmp/cache levels=1:2 keys_zone=netkiller:128m inactive=1m; 2 3 server { 4 listen 8080; 5 server_name localhost; 6 7 location / { 8 try_files $uri @backend; 9 } 10 11 location @backend { 12 proxy_pass http://node1.netkiller.cn:8080; 13 proxy_cache netkiller; 14 proxy_cache_methods POST; 15 proxy_cache_key "$request_uri|$request_body"; 16 proxy_buffers 8 32k; 17 proxy_buffer_size 64k; 18 proxy_cache_valid 5s; 19 proxy_cache_use_stale updating; 20 add_header X-Cached $upstream_cache_status; 21 } 22 }
2.3.12.11. $request_body - HTTP POST 数据
2.3.12.11.1. 用户日志
将 POST 数据记录到日志中
1log_format main '$remote_addr - $remote_user [$time_local] "$request" ' 2 '$status $body_bytes_sent "$http_referer" ' 3 '"$http_user_agent" "$http_x_forwarded_for" - "$request_body"';
注意:用户登录通常使用POST方式,所以记录POST数据到日志会带来安全问题,例如用户密码泄露。