nginx return将http响应头内容类型从application/pdf更改为text/html

分享于 

4分钟阅读

互联网

 

问题:

想从这个url重定向:

localhost:80/files/1.pdf

到此url:

localhost:80/viewer.html?pdf=/files/1.pdf

我使用Nginx return来执行以下操作:


location ~* /files/(.+.pdf)$ {


 return $scheme://$host:$server_port/viewer.html?pdf=/files/$1;


}



viewer.html使用PDF.js并尝试打开url参数中给出的pdf并记录它页面数:


<html lang="en">


<head>


 <meta charset="UTF-8">


 <script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@2.3.200/build/pdf.min.js">


 </script>


</head>


<body>


<script>


 const queryString = window.location.search; // has the params of the url


 const urlParams = new URLSearchParams(queryString); //parses the params


 const filePath = urlParams.get('pdf');


 var loadpdf = pdfjsLib.getDocument(filePath);



 loadpdf.promise.then(function(document) {


 console.log(document._pdfInfo.numPages);


 }, function (reason) { // PDF loading error


 console.error(reason);


 });


</script>


</body>


</html>



当重定向发生时,pdf的HTTP GET响应头有Content-Type:text/html instead of application/pdf and the pdf can no longer be read.


答案1:

尝试这个:

Nginx配置:


 location ~* ^/.*.pdf$ {


 if ( $query_string !~"noredir" ) {


 rewrite /(.*.pdf)$ viewer.html?pdf=$1 redirect;


 }


 try_files $uri =404;


 }



viewer.html(在文件路径中添加adds?noredir):


<html lang="en">


<head>


 <meta charset="UTF-8">


 <script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@2.3.200/build/pdf.min.js">


 </script>


</head>


<body>



<canvas id="the-canvas"></canvas>



<script>


 const queryString = window.location.search; // has the params of the url


 const urlParams = new URLSearchParams(queryString); //parses the params


 const filePath = urlParams.get('pdf') +"?noredir";


 var loadpdf = pdfjsLib.getDocument(filePath);


 console.log(filePath);



 loadpdf.promise.then(function(pdf) {


 console.log('PDF loaded');



 // Fetch the first page


 var pageNumber = 1;


 pdf.getPage(pageNumber).then(function(page) {


 console.log('Page loaded');



 var scale = 1.5;


 var viewport = page.getViewport({scale: scale});



 // Prepare canvas using PDF page dimensions


 var canvas = document.getElementById('the-canvas');


 var context = canvas.getContext('2d');


 canvas.height = viewport.height;


 canvas.width = viewport.width;



 // Render PDF page into canvas context


 var renderContext = {


 canvasContext: context,


 viewport: viewport


 };


 var renderTask = page.render(renderContext);


 renderTask.promise.then(function () {


 console.log('Page rendered');


 });


 });


 }, function (reason) {


 // PDF loading error


 console.error(reason);


 });


</script>


</body>


</html>



这是基于github上的pdf.js例子



文本  TEX  HTTP  type  HEAD  Header  
相关文章