功能需求:由于公司有很多的日志文件需要整理,并且需要相关人员去下载查看,为了简便,我搭建了nginx服务并且将日志文件 放到 相应的目录下,用以方便相关人员下载查看,于是很快把nginx服务就搭建完了,但是尴尬的事情出现了,当点击日志文件时发现txt结尾的文档,直接被浏览器打开了,几千行的数据全都打印在浏览器上。于是就想到将nginx配置成可下载的。
1.环境
系 统: Centos6.5
基础服务: Nginx 版本 nginx/1.6.0
2.修改配置文件,以支持 以txt 结尾的文件能够实现下载而不是直接在浏览器打开;
配置详情:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| server {
listen 80; #这些都是基础配置了 监听端口
server_name localhost; # 主机名
autoindex on; #nginx 目录浏览功能 默认是
#access_log logs/host.access.log main;
location / {
if ($request_filename ~* ^.*?\.(txt)$)
{
add_header Content-Disposition 'attachment:';
add_header Content-Type: 'APPLICATION/OCTET-STREAM';
}
root /html;
index index.html index.htm;
}
}
|
注:在开启下载功能时,最关键的配置:
1
2
3
4
5
| if ($request_filename ~* ^.*?\.(txt)$)
{
add_header Content-Disposition 'attachment:';
add_header Content-Type: 'APPLICATION/OCTET-STREAM';
}
|
这段配置的意义在于,当接收到以txt为结尾的链接请求时,会转为下载,其中 Content-Disposition 属性名 attachment 则是附件下载。 注意: 大部分的资料和博客都是这么配置的,但是会发现,设置完成后点击nginx目录下txt文件确实是下载了,不是在浏览器中打开,但是,在chrome 或者 其他浏览器中,仍然是在浏览器中显示,而没有实现下载。 重点关键在attachment: 应该注意一个这样的现象
Google chrome:Content-Disposition: attachment firefox : Content-Disposition attchement 注意这里是没有冒号, 如果配置为add_header Content-Disposition 'attachment:'; 则出现的效果为 火狐点击txt文件时,会提供下载,而不会在浏览器打开,而chrome 浏览器则是会在浏览器中显示 如果配置为add_header Content-Disposition 'attachment'; 则无论在火狐还是chrome浏览器中点击txt文件时都会为下载。
|