通过第三方组件file_md5实现。
首先下载file_md5模块(使用wget也可以,我这边是在内网中使用)
下载地址为:https://codeload.github.com/cfsego/file-md5/zip/refs/heads/master
在nginx中增加该模块(pcre以及openssl依赖包已安装)
1.将nginx安装包及file_md5安装包解压
2.执行./configure --with-http_ssl_module --add-module=../file-md5-master(ssl模块根据需求)
3.make;make install
4.在/usr/local/nginx/conf/nginx.conf的location节点下增加md5配置
location /Download/
{
add_header Content-MD5 $file_md5;
alias /home/test/filepath/;
}
测试,header中已增加Content-MD5,内容即为test.txt的MD5码。
curl -i -k https://127.0.0.1:17129/Download/test.txt
HTTP/1.1 200 OK
Server: nginx/1.20.2
Date: Thu, 24 Mar 2022 01:42:15 GMT
Content-Type: text/plain
Content-Length: 4
Last-Modified: Thu, 24 Mar 2022 01:41:27 GMT
Connection: keep-alive
ETag: "623bcc47-4"
Content-MD5: 1181c1834012245d785120e3505ed169
Accept-Ranges: bytes
111(文件内容)
接下来,是我这边的需求,不返回文件内容,只返回MD5码,思路就是替换返回的内容,使用return 就可以实现该功能。
location /Download/
{
#add_header Content-MD5 $file_md5;
alias /home/test/filepath/;
return 200 $file_md5;
}
使用curl -i -k https://127.0.0.1:17129/Download/test.txt测试,结果如下
HTTP/1.1 200 OK
Server: nginx/1.20.2
Date: Thu, 24 Mar 2022 02:05:43 GMT
Content-Type: text/plain
Content-Length: 32
Connection: keep-alive
1181c1834012245d785120e3505ed169
完毕。