工程組件-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就可以了

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