1.前端代码修改把第三方图片地址进行替换
原始图片地址:
http://192.168.1.1/pic?8dd611z2c-=s0931065c3614e-=t1i5m*=p4p9i=d1si4d667d8=*5b8i2e=
前端把原始地址替换:
http://192.168.2.5:80/crossOriginImg?referer=http://192.168.1.1/pic?8dd611z2c-=s0931065c3614e-=t1i5m*=p4p9i=d1s*i4d66*7d8=*5b8i2e=
把IP端口指定到本地同源的可以部署nginx的服务器,把源地址当作一个参数传到nginx进行解析,这样不需要提前知道第三方图片地址ip和端口。
2.配置NGINX
location ~/crossOriginImg {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
if ($args ~ "referer=(.*)"){
set $newurl "$1";
}
proxy_pass $newurl;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_intercept_errors on;
error_page 301 302 307 = @handle_redirect;
}
location @handle_redirect {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
set $saved_redirect_location '$upstream_http_location';
proxy_pass $saved_redirect_location;
}
配置说明:
1.添加允许跨域的请求头
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
2.$args拿到地址中所有参数再正则匹配拿到原始图片地址,通过proxy_pass 代理到新的地址,这里不使用$arg_referer因为当图片地址有包含其他参数时会取不到完整的地址
if ($args ~ "referer=(.*)"){
set $newurl "$1";
}
proxy_pass $newurl;
3.为了解决原始图片会自动跳转到其他地址返回301时,在重定向的响应头中拿到跳转后地址$upstream_http_location,进行二次代理
location @handle_redirect {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
set $saved_redirect_location '$upstream_http_location';
proxy_pass $saved_redirect_location;
}