业务场景:
静态资源服务器有一部分js不允许直接http://host:port/xxxx.js访问,需要进行一层后端验证,期望是http://host:port/xxxx.js/key访问原来的静态资源服务器,这个key可以被后端验证,
如果验证成功,则成功访问资源,如果验证失败,就返回 403.
解决方案:
使用nginx对资源做一层拦截,不带验证参数key访问的时候,或者携带验证参数但是验证失败的时候,返回403,验证通过则可以访问静态资源。
1. 安装nginx
wget http://nginx.org/download/nginx-1.19.8.tar.gz
wget https://github.com/openresty/headers-more-nginx-module/archive/refs/heads/master.zip
unzip master.zip
tar -xzvf nginx-1.19.8.tar.gz
cd nginx-1.19.8
./configure --prefix=/root/nginx/nginx1.19.8 --with-compat --with-file-aio --with-threads --with-http_stub_status_module --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --add-module=../headers-more-nginx-module-master
make
make install
第一个是下载 nginx , 第二个是下载 headers-more-nginx-module模块,自定义返回头
····· 编译···········安装
在 /root/nginx/nginx1.19.8可以看到已经安装好的nginx目录,进入conf
cd /root/nginx/nginx1.19.8/conf
编辑nginx.conf
比如我现在的地址是 http://192.168.137.101/
我需要访问的资源是
http://192.168.137.101/static/index.js/key
nginx配置如下:
location ~/static/(.*)/(.*) {
auth_request /auth;
set $auth_request_uri "http://192.168.137.1:8813/api/403?key=$2";
more_set_headers "Content-Type:application/javascript;";
alias /root/nginx/nginx1.19.8/html/static/$1;
}
location /auth {
internal;
proxy_pass $auth_request_uri;
proxy_pass_request_body off;
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
}
location /static/ {
deny all;
}
1.第一个location 是一个正则匹配,匹配访问static下的静态资源,两个参数分别可以用$1,$2获得。 more_set_headers "Content-Type:application/javascript;"; 是我把返回头类型修改成js类型,如果你是对图片资源或者其他资源加拦截,记得自己修改对应的Content-Type。 http://192.168.137.1:8813/api/403?key=$2 是我后端验证用的,自行可以用编程语言实现。
2.第二个location是 对静态资源的后端拦截,如果非200,是不可能跳转到相应的资源的
3.因为nginx是按照location进行匹配的,此时直接访问static下的js都是403的。