默認(rèn)情況下通過Nginx服務(wù)器來訪問txt等文件,會(huì)在瀏覽器上直接打開.如果想要實(shí)現(xiàn)下載文件的效果,則需要在nginx服務(wù)端做一些設(shè)置
在nginx.conf追加server
server {
listen 10086;
# 根目錄設(shè)置
root /opt/downloads;
# 啟用目錄列表
location / {
autoindex on; # 啟用目錄列表
autoindex_exact_size off; # 以更人性化的格式顯示文件大小
autoindex_localtime on; # 以服務(wù)器本地時(shí)間顯示文件時(shí)間
charset utf-8; # 設(shè)置字符集為 UTF-8
try_files $uri $uri/ =404; # 確保請(qǐng)求的文件或目錄存在,否則返回 404
add_header Content-Type appliction/octet-stream;
add_header Content-Disposition attachment;
}
# 禁止訪問上級(jí)目錄,防止目錄遍歷攻擊
location ~ /\.\./ {
deny all;
}
# 禁止訪問 .js* 文件
location ~ /\.js {
deny all;
}
}
擴(kuò)展說明:
Content-Disposition:
默認(rèn)模式,以頁(yè)面的一部分或者整個(gè)頁(yè)面的形式展示
Content-Disposition inline
指定附件模式
Content-Disposition attachment
指定附件模式并指定被下載文件的名稱
Content-Disposition attachment; filename="filename.jpg"
Content-Type:
application/xhtml+xml :XHTML格式
application/xml : XML數(shù)據(jù)格式
application/atom+xml :Atom XML聚合格式
application/json : JSON數(shù)據(jù)格式
application/pdf :pdf格式
application/msword : Word文檔格式
application/octet-stream : 二進(jìn)制流數(shù)據(jù)(如常見的文件下載)