工程组件-nginx提供文件下载功能

背景

nginx是开发中的利器,本wiki将阐述如何使用nginx制作一个文件下载服务器。

实战过程

docker默认安装nginx

sudo docker run -d --name nginx -p 9008:80 nginx:stable
浏览器访问9008端口
在这里插入图片描述

sudo docker exec -it nginx bash
cd /etc/nginx
# 查看默认配置文件
cat nginx.conf
cat conf.d/default.conf

nginx.conf默认配置如下

# 全局块配置指令(从开始截止到event,都数据全局配置指令)
user  nginx; # 配置用户或者组
worker_processes  1; # 工作进程数

error_log  /var/log/nginx/error.log warn; # 指定错误日志路径和级别
pid        /var/run/nginx.pid; # 指定运行进程存储文件(里面都是运行的进程id)


# event块
events {
    worker_connections  1024; # 每个进程最大的连接数,默认512
}


http {
    include       /etc/nginx/mime.types; # 文件扩展名与文件类型映射表
    default_type  application/octet-stream; # 默认文件类型

	# 指定日志格式
    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  /var/log/nginx/access.log  main; # 指定日志存储路径

    sendfile        on; # 允许sendfile方式传输文件
    #tcp_nopush     on;

    keepalive_timeout  65; # http长连接超时时间

    #gzip  on; # 是否开启gzip

    include /etc/nginx/conf.d/*.conf; # 激活其他的配置文件
}

在这里插入图片描述

default.conf的配置如下:

server {
    listen       80; # 监听端口
    server_name  localhost; # 监听地址

    #charset koi8-r;
    #access_log  /var/log/nginx/host.access.log  main;

    location / { # 路由设置
        root   /usr/share/nginx/html; # 根路径
        index  index.html index.htm; # 指定默认页
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    #
    #location ~ \.php$ {
    #    root           html;
    #    fastcgi_pass   127.0.0.1:9000;
    #    fastcgi_index  index.php;
    #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
    #    include        fastcgi_params;
    #}

    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #
    #location ~ /\.ht {
    #    deny  all;
    #}
}

从上面的配置可以看到,sendfile 设置为了on,说明可以进行文件传输

我们直接利用根目录的路由目录,在html目录中添加一个文件,然后再访问一下名称看看效果。

cd /usr/share/nginx/html
touch my_file

在浏览器方位http://ip:9008/my_file,可以开始下载了
在这里插入图片描述

评价

重点设置一下sendfile on,剩下的直接配置location就可以了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章