openresty+pdf.js 实现阿里云oss pdf 文件预览
以前有基于openresty + pdf.js 实现了pdf 文件预览的方案,但是对于阿里的oss 这个就有些不一样了(因为oss 有安全签名的处理)
问题说明
以前对于文件proxy 的配置
location /pdf {
proxy_redirect off;
# 开启了跨域访问,实际可以不用
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods GET, POST, PUT, DELETE, OPTIONS;
// 此处是核心
proxy_set_header Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_body_buffer_size 10M;
client_max_body_size 10G;
set $agent "Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5";
set_by_lua_block $oss_url {
local ossurl= ngx.req.get_uri_args()["ossurl"];
ngx.log(ngx.ERR, "error: ", ossurl)
return ossurl
}
proxy_buffers 1024 4k;
proxy_read_timeout 300;
proxy_connect_timeout 80;
proxy_set_header User-Agent $agent;
proxy_pass $oss_url;
# 配置cache
proxy_cache pdf;
proxy_cache_key $scheme$proxy_host$uri$is_args$args;
proxy_cache_valid 200 304 302 24h;
}
解决方法
对于host 的传递使用$proxy_host 变量,这样可以保证传递的host 是正确的,oss 签名校验就没问题了,参考配置
location /pdf {
proxy_redirect off;
# 开启了跨域访问,实际可以不用
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods GET, POST, PUT, DELETE, OPTIONS;
proxy_set_header Host $proxy_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_body_buffer_size 10M;
client_max_body_size 10G;
set $agent "Mozilla/5.0 (iPad; U; CPU OS 4_3_3 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8J2 Safari/6533.18.5";
set_by_lua_block $oss_url {
local ossurl= ngx.req.get_uri_args()["ossurl"];
ngx.log(ngx.ERR, "error: ", ossurl)
return ossurl
}
proxy_buffers 1024 4k;
proxy_read_timeout 300;
proxy_connect_timeout 80;
proxy_set_header User-Agent $agent;
proxy_pass $oss_url;
# 配置cache
proxy_cache pdf;
proxy_cache_key $scheme$proxy_host$uri$is_args$args;
proxy_cache_valid 200 304 302 24h;
}
参考资料
https://www.cnblogs.com/rongfengliang/p/13693067.html
http://nginx.org/en/docs/varindex.html
http://nginx.org/en/docs/http/ngx_http_proxy_module.html#var_proxy_host