一、前言

nginx的配置这块和普通的一样就可以了,只要在nginx/html 目录新增文件即可。然后通过Nginx的IP加上文件的路径即可下载,比如在nginx/html目录创建一个test目录,然后在test目录在创建一个001.txt文件,最在浏览器输入 http://localhost:10007/01/001.txt 即可进行下载。

二、静态文件下载

上述的配置可以简单满足一些要求,但是有时候我们想通过nginx进行下载其他的格式的文件时候,比如下载一张图片,但是访问这个url浏览器会自动展现这张图片,那么这时我们就可以通过增加配置,并且让浏览器下载该图片。
例如,我们在访问test目录的静态文件,那么我们在nginx/conf中添加如下配置即可!

1
2
3
location / {
add_header Content-Disposition "attachment;";
}

未加配置的时候:

添加配置的时候:

三、指定文件存放路径

Nginx的文件路径默认在安装的nginx/html 目录下,如果我们想改变这路径,可以将location 的root 路径进行更改,比如更改到/opt/soft/wno704/images目录下 :

1
2
3
4
location / {
root /opt/soft/wno704/images;
index index.html index.htm;
}

如果配置多个目录,路径指定用“alias”,具体如下:

1
2
3
4
5
6
7
8
9
location /file {
alias /opt/file;
index index.html index.htm;
}

location /image {
alias /opt/image;
index index.html index.htm;
}

四、nginx/conf 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
http {
include mime.types;
default_type application/octet-stream;

sendfile on;
#tcp_nopush on;
server_tokens off;
#keepalive_timeout 0;
keepalive_timeout 65;
client_body_timeout 100;
client_header_timeout 100;
send_timeout 100;

limit_conn_zone $binary_remote_addr zone=conn_zone:100m;

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

access_log logs/access.log main;

server {
listen 10007;
server_name localhost;
location / {
root /opt/soft/wno704/images;
index index.html index.htm;
add_header Content-Disposition "attachment;";
}

location /file {
alias /opt/file;
index index.html index.htm;
add_header Content-Disposition "attachment;";
}

location /image {
alias /opt/image;
index index.html index.htm;
add_header Content-Disposition "attachment;";
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}