如何在nginx中完全下载资源时如何通知

问题描述 投票:3回答:1

我需要知道从服务器完全下载资源。我的服务器配置了NginX Web服务器,当且仅当资源完全由用户下载时,我想做一些事情。

nginx webserver rsyslog
1个回答
7
投票

如果您使用Nginx来处理下载文件(使用XSendfile),您应该在Nginx配置(在“服务器”块中)的下载处理块中添加特定的access_log块。它会是这样的:

location /download_music/ {
            internal;
            root /usr/share/nginx/MY_SITE/media/music;
            access_log /var/log/nginx/download.MY_SITE.log download;
    }

access_log行末尾的“download”一词实际上是一种日志格式,您应该将其添加到“http”块中的nginx主配置文件(/etc/nginx/nginx.conf)。它可能是这样的:

http {
    ...

    log_format download '{ "remote_addr" : "$remote_addr", "time":"$time_local", "request":"$request", '
                  '"traffic":$body_bytes_sent, "x_forwarded_for":"$http_x_forwarded_for" }';

    ...
}

您可以将此格式更改为您想要的格式(稍后您将在脚本中使用它)。如果您监视此日志文件(使用“tail -f /var/log/nginx/download.MY_SITE.log”),您将看到每次下载暂停或完成下载时,都会在此文件中添加一行日志。下一步是使用rsyslog和“imfile”和“omprog”模块。您应该在rsyslog(/etc/rsyslog.conf)的配置文件末尾添加这些配置:

$ModLoad imfile
$InputFileName /var/log/nginx/download.MY_SITE.log
$InputFileTag nginx-access
$InputFileStateFile state-nginx-access
$InputFileSeverity info
$InputFileFacility local3
$InputFilePollInterval 1
$InputRunFileMonitor

$ModLoad omprog
$actionomprogbinary /usr/share/nginx/MY_SITE/scripts/download.py
$template LogZillaDbInsert,"%hostname:::lowercase%\9%pri%\9%programname%\9%msg%\n"
local3.* :omprog:;RSYSLOG_TraditionalFileFormat

注意这一行:

/usr/share/nginx/MY_SITE/scripts/download.py

这是脚本的地址,每次将日志条目添加到日志文件时都会调用该脚本,并且在此脚本中将使用(在Python代码中)提供整个日志条目:

line = sys.stdin.readline()

然后,您可以解析该行并查找已记录的内容,包括下载的文件大小(在每个暂停/结束事件上)。现在,您只需在下载URL中包含文件大小,然后在此脚本中检索它,并将其与下载的字节进行比较。如果这两个数字相等,则表示下载已成功完成。此外,您可以在此脚本中执行任何其他操作(例如,过期下载链接,增加数据库的下载次数,...)

© www.soinside.com 2019 - 2024. All rights reserved.