nginx 实现文件下载
需求:把一個文件,對外提供url路徑,來完成文件下載。
?修改nginx配置文件
? 先看配置文件
server {listen 80;server_name localhost;location ^~ /download/ {alias /home/webhtml/;if ($request_filename ~* ^.*?\.(html|doc|pdf|zip|docx|txt)$) {add_header Content-Disposition attachment;add_header Content-Type application/octet-stream;}sendfile on; # 開啟高效文件傳輸模式autoindex on; # 開啟目錄文件列表autoindex_exact_size on; # 顯示出文件的確切大小,單位是bytesautoindex_localtime on; # 顯示的文件時間為文件的服務器時間charset utf-8,gbk; # 避免中文亂碼} }?
?關鍵點解析:
? 其中?
server_name ?localhost;? 代表服務名,在這里直接訪問 127.0.0.1就可以。如果是別的機器訪問這臺機器。則直接替換成這臺機器的地址即可。
?location ^~ /download/?帶邊的是攔截包含?download的請求
?alias /home/webhtml/;? 是來配置下載文件的路徑,也就是提供下載的文件要在這個路徑下。
??if ($request_filename ~* ^.*?\.(html|doc|pdf|zip|docx|txt)$) {
? ? ? ? ? ? add_header Content-Disposition attachment;
? ? ? ? ? ? add_header Content-Type application/octet-stream;
? ? ? ? }
這段代碼,會去判斷文件的后綴。以及提供下載功能。
修改完配置文件重啟nginx即可。這里不提供命令了。我是用docker的形式,比較簡單。直接一個?docker?restar?nginx就行了。不過我提供一片文章:nginx重啟幾種方法 - 習慣沉淀 - 博客園
使用例子
? ?首先把一個待下載的文件放在:/home/webhtml/?目錄下
? 例如:
然后就可以用這個url來下載文件了(本機訪問): 127.0.0.1/download/hello.txt
一般都是對外提供下載的(假設我這臺部署nginx的機器是:10.2.5.10):10.2.5.10/download/hello.tx??
我們可以知道的是,帶有download的路徑被攔截了,加上我們配的文件路徑,最后去取文件:
/home/webhtml/hello.txt
?
??
總結
以上是生活随笔為你收集整理的nginx 实现文件下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 8种常见液相色谱异常峰
- 下一篇: Struts2中s标签的用法