技术实践

《关于nginx修改Header参数》

这里需要注意的是通过proxy_hide_header隐藏原有的属性,然后在通过add_header添加,我也是查了一些资料,才知道原因所在

羊先生的头像
羊先生2022.02.21 · 3 分钟阅读 · 39 阅读
《关于nginx修改Header参数》封面
文章正文还需 3 分钟

遇到一个问题,就是https://public.creditchina.gov.cn,这个信任中国返回的pdf文件,但是个下载,我想把这个pdf预览放到网页里面去查看

没用nginx之前

html 复制代码
https://public.creditchina.gov.cn/xxxxx/xxxxx/xxx.pdf

把这个地址输入到浏览器中,自动就变成了下载

Content-Disposition

打开浏览器器控制台可以发现,在返回的头部有这个参数Content-Disposition,

Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。Content-disposition其实可以控制用户请求所得的内容存为一个文件的时候提供一个默认的文件名,文件直接在浏览器上显示或者在访问时弹出文件下载对话框

此时就要想办法吧这个参数的给弄掉

nginx完整的配置

nginx 复制代码
#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #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  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen  8888;
		
		server_name 127.0.0.1;

		location / {
            if ($request_method ~* "(GET|POST)") {
			  add_header "Access-Control-Allow-Origin"  *;
			}

			# Preflighted requests
			if ($request_method = OPTIONS ) {
			  add_header "Access-Control-Allow-Origin"  *;
			  add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD";
			  add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
			  return 200;
			}
            
			proxy_pass http://www.baidu.com/;
            proxy_redirect default;
		}
		
		location /pdfview{
            rewrite  ^/pdfview/(.*)$ /$1 break;
			proxy_pass https://public.creditchina.gov.cn/;
			proxy_set_header Upgrade $http_upgrade;
			proxy_set_header Connection "Upgrade";
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_set_header X-Real-IP $remote_addr;
			
			proxy_hide_header 'Content-Disposition';
			proxy_hide_header 'Content-Type';
			add_header 'Content-Type' 'application/pdf';
			add_header 'Content-Disposition' '';
        }	
       
    }
}

测试:127.0.0.1:8888/pdfview/xxxx/xxx/xxx.pdf,就会变成预览

这里需要注意的是通过proxy_hide_header隐藏原有的属性,然后在通过add_header添加,我也是查了一些资料,才知道原因所在