RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:9:30-18:00
扫码咨询
关闭右侧工具栏
Nginx配置实现下载文件的示例代码
  • 作者:admin
  • 发表时间:2020-11-21 07:50
  • 来源:未知

这篇文章主要介绍了Nginx配置实现下载文件的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

偶尔听人说用nginx实现文件上传下载,之前看nginx实践大致看到过,没有细究。所以今天就想研究下nginx实现文件的上传下载,直接开搞,本地服务启起。这里记录下配置及踩坑记录。

一、配置

http {
 ...
 server: {
 # 配置下载
  location /download {
   root D:\\download;
   autoindex on;
   autoindex_exact_size off;
  }
 }
 ...
}http {
 ...
 server: {
 # 配置下载
  location /download {
   root D:\\download;
   autoindex on;
   autoindex_exact_size off;
  }
 }
 ...
}

这是目录里随便放的几个文件,可以看到实现成功。

这里踩过几个坑,下面提示下:

1、root路径配置问题

刚开始配置的 alias D:\download,报错:2020/08/14 10:36:06 [emerg] 26396#16140: invalid number of arguments in "alias" directive in D:\Program File\nginx\nginx-1.13.12/conf/nginx.conf:74

那么查配置 74 行,发现少了分号,加上问题依旧。换成 root D:\download;,报错:2020/08/14 10:44:20 [emerg] 21376#17156: invalid number of arguments in "root" directive in D:\Program File\nginx\nginx-1.13.12/conf/nginx.conf:74

问题依旧,后来发现路径有问题,写错了,应该是

root D:/download;
// 或者
root D:\\download;

原因都懂,就是 \ 只是个转义字符,要么用 \\,要么就用 /

2、root与alias差别

ok,这样配置可以了。但是当我输入:http://localhost/download/,报错404,我的D盘目录下为D:/download/*,然后其他文件

刚开始报错:2020/08/14 11:02:49 [error] 9928#12876: *11 CreateFile() "D:\download\/download" failed (2: The system cannot find the file specified), client: 127.0.0.1, server: , request: "GET /download HTTP/1.1", host: "localhost"

看到这个路径D:\download\/download这里有问题,所以我把配置rootD:/download/;,后面的 / 去掉了,再试,还是报错:2020/08/14 11:04:15 [error] 3128#11636: *1 CreateFile() "D:\download/download" failed (2: The system cannot find the file specified), client: 127.0.0.1, server: , request: "GET /download HTTP/1.1", host: "localhost"

所以考虑到不是路径的问题,那么问题原因在哪?在于 root 与 alias 配置的区别。

也就是说 当 rootD:/download; 时,你请求http://localhost/download/,他找的是:D:\download\download

而当 a唐山网络公司lias D:/download; 时,你请求http://localhost/download/,他找的才是:D:\download