Nginx 文件目录页美化
网上大部分是修改源码来实现,但我不喜欢折腾源码编译,所以使用了一些神奇的方法。
Nginx(Debian:nginx-full)中有两个神奇的指令,add_before_body
与add_after_body
,分别用来在响应内容前后插入内容,所以只要注入到末尾,用Javascript
处理就行了。
location / {
# ......
add_after_body .uindex.html;
}
在目录下创建一个隐藏文件.uindex.html
:
<!-- uindex -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha512-Dop/vW3iOtayerlYAqCgkVr2aTr2ErwwTYOvRFUpzl2VhCMJyjQF0Q9TjUXIo6JhuM/3i0vVEt2e/7QQmnHQqw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script>
let dirlist = $("pre").html().split("\n");
function getFileInfo(line) {
line = line.replace(' ', '|');
line = line.replace('<a href="', '');
line = line.replace('">', '|');
line = line.replace('</a>', '|');
line = line.split('|');
temp = [];
for(i in line) {
if(line[i] != "") temp.push(line[i].replace(/(^\s*)|(\s*$)/g, ""));
}
line = null;
//if(temp.length < 3) return [];
return temp;
}
function outputHtml(dirlist) {
let list = [];
for(i in dirlist) {
let temp = getFileInfo(dirlist[i]);
if(temp) list.push(temp);
}
let temp = '';
list.forEach((i) => {
if(i.length >= 2) {
if(i.length > 3) {
temp += `<tr><td><a href="${i[0]}">${i[1]}</a></td><td>${i[2].replace(' -','')}</td><td>`;
temp += `${i[3]}</td></tr>`;
} else if(i.length == 2) {
temp += `<tr><td><a href="${i[0]}">${i[1]}</a></td><td></td><td></td></tr>`;
} else {
temp += `<tr><td><a href="${i[0]}">${i[1]}</a></td><td>${i[2].replace(' -','')}</td><td>`;
temp += `</td></tr>`;
}
}
});
return `<div class="container"><div class="row"><div class="col-md-12"><table class="table table-striped table-hover">
<caption class="h3">${$("h1").text()}</caption>
<thead><tr><th>fileName</th><th>date</th><th>size</th></tr></thead><tbody>${temp}</tbody></table></div></div></div><p style="text-align:center;font-size:14px;color:#dddddd;text-align:center;font-size:14px;color:#dddddd;">© 2021 uindex.</p>`;
}
$(() => {
//$("body").css({"display": "none"})
let html = outputHtml(dirlist);
$("h1").remove();
$("hr").remove();
$("pre").remove();
$("body").append(html);
//$("body").css({"display": "inline"})
});
</script>
不会正则,所以先替换再分割了一遍,旨在能用就行。使用时会一闪一下,正常。