网络上很多使用nginx来作为文件服务器的,前段时间公司也有这个需求,就研究了一下使用nginx来做文件服务器,参见前面两篇文章:

容器中使用ngnix搭建支持上传下载的文件服务器 容器中使用nginx并搭建sftp服务

但是nginx原生的autoindex显示界面很一般,网上也有使用 Nginx-Fancyindex插件来的,但是需要自己编译nginx,比较麻烦,笔者使用的容器版本的nginx,所以放弃了它,而选择了add_after_body的方式。

感谢 phuslu 写了一个 autoindex.html,可以非常方便的进行美化,只需要在nginx配置中添加一行:

1add_after_body /autoindex.html;

非常方便。

作者的展示站点: https://phus.lu/

它还支持展示目录中的README.md文件,非常不错。

在站点中,作者为了方便大家获取autoindex.html,将其放在了文件服务器中显示。在实际应用中,该文件不应该让大家看到,可以将其改为隐藏文件,即改名为.autoindex.html。但是如果文件服务器的下载目录同时是为了方便别人上传文件(上传的人只能访问此目录),此时有不相关的文件就不太合适了。所以笔者修改了相应的配置,将autoindex.html放在了另一个目录,这里列一下nginx的主要配置:

 1server {
 2		......
 3		root share;
 4        charset utf-8;
 5
 6        add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
 7
 8        add_header cache-control "no-cache";
 9        add_header access-control-allow-origin "*";
10        add_header referrer-policy "no-referrer";
11        add_header x-content-type-options nosniff;
12        add_header x-xss-protection "1; mode=block";
13        add_header x-frame-options sameorigin;
14
15        location = /autoindex.html {
16            root   html;
17        }
18        
19        location / {
20            autoindex       on;
21            autoindex_localtime on;
22            autoindex_exact_size off;
23            add_after_body /autoindex.html;
24        }
25        
26        location ~ \.(md|ini|txt|log|pac|keys|lua|json|yaml|toml|conf|cmd|sh|bash|h|c|cpp|hpp|py|go|service)$ {
27            default_type text/plain;
28        }
29
30        location ~ ^/(bashrc|vimrc)$ {
31            default_type text/plain;
32        }
33        ......

作者还写了一个markdown.html用于渲染markdown文件为html,但是有一个问题就是导致下载的所有的md文件后面都有markdown.html的代码。笔者通过研究,在展示后面加了一列preview,如果是markdown文件,则会在后面显示一个preview按钮,点它则会新建一个窗口,来展示经过html渲染的markdown文件(markdown的是通过marked来渲染的,功能有限)。如下图所示:

附上autoindex.html:

  1
  2<!-- autoindex.html 20221104 for nginx, see https://phus.lu -->
  3<script>
  4var marked_js = 'https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/marked/4.0.2/marked.min.js'
  5var github_markdown_css = 'https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/github-markdown-css/5.1.0/github-markdown-light.min.css'
  6!function(){
  7	var website_title = ''
  8	var max_name_length = 60
  9	var datetime_format = '%Y-%m-%d %H:%M:%S'
 10	var enable_readme_md = true
 11	var enable_footer_js = true
 12
 13	var dom = {
 14		element: null,
 15		get: function (o) {
 16			var obj = Object.create(this)
 17			obj.element = (typeof o == "object") ? o : document.createElement(o)
 18			return obj
 19		},
 20		add: function (o) {
 21			var obj = dom.get(o)
 22			this.element.appendChild(obj.element)
 23			return obj
 24		},
 25		text: function (t) {
 26			this.element.appendChild(document.createTextNode(t))
 27			return this
 28		},
 29		html: function (s) {
 30			this.element.innerHTML = s
 31			return this
 32		},
 33		attr: function (k, v) {
 34			this.element.setAttribute(k, v)
 35			return this
 36		}
 37	}
 38
 39	head = dom.get(document.head)
 40	head.add('meta').attr('charset', 'utf-8')
 41	head.add('meta').attr('name', 'viewport').attr('content', 'width=device-width,initial-scale=1')
 42
 43	if (!document.title) {
 44		document.write(["<div class=\"container\">",
 45		"<h3>nginx.conf</h3>",
 46		"<textarea rows=8 cols=50>",
 47		"# download autoindex.html to /wwwroot/",
 48		"location ~ ^(.*)/$ {",
 49		"    charset utf-8;",
 50		"    autoindex on;",
 51		"    autoindex_localtime on;",
 52		"    autoindex_exact_size off;",
 53		"    add_after_body /autoindex.html;",
 54		"}",
 55		"</textarea>",
 56		"</div>"].join("\n"))
 57		return
 58	}
 59
 60	var bodylines = document.body.innerHTML.split('\n')
 61	document.body.innerHTML = ''
 62
 63	titlehtml = document.title.replace(/\/$/, '').split('/').slice(1).reduce(function(acc, v, i, a) {
 64		return acc + '<a href="/' + a.slice(0, i+1).join('/') + '/">' + v + '</a>/'
 65	}, '<a href="/">Index</a> of /')
 66	if (website_title) {
 67		document.title = website_title + ' - ' + document.title
 68	}
 69	head.add('meta').attr('name', 'description').attr('content', document.title)
 70
 71	div = dom.get('div').attr('class', 'container')
 72	div.add('table').add('tbody').add('tr').add('th').html(titlehtml)
 73	tbody = div.add('table').attr('class', 'table-hover').add('tbody')
 74
 75	names = ['Name', 'Date', 'Size']
 76	thead = tbody.add('tr')
 77	for (i = 0; i < names.length; i++)
 78		thead.add('td').add('a').attr('href', 'javascript:sortby('+i+')').attr('class', 'octicon arrow-up').text(names[i]);
 79	thead.add('td').attr('class', 'octicon').text('preview')
 80
 81	var insert = function(filename, datetime, size) {
 82		if (/\/$/.test(filename)) {
 83			css = 'file-directory'
 84			size = ''
 85		} else if (/\.(zip|7z|bz2|gz|tar|tgz|tbz2|xz|cab)$/.test(filename)) {
 86			css = 'file-zip'
 87		} else if (/\.(py|js|php|pl|rb|sh|bash|lua|sql|go|rs|java|c|h|cpp|cxx|hpp)$/.test(filename)) {
 88			css = 'file-code'
 89		} else if (/\.(jpg|png|bmp|gif|ico|webp)$/.test(filename)) {
 90			css = 'file-media'
 91		} else if (/\.(flv|mp4|mkv|avi|mkv|vp9)$/.test(filename)) {
 92			css = 'device-camera-video'
 93		} else {
 94			css = 'file'
 95		}
 96
 97		displayname = decodeURIComponent(filename.replace(/\/$/, ''))
 98		if (displayname.length > max_name_length)
 99			displayname = displayname.substring(0, max_name_length-3) + '..>';
100
101		if (!isNaN(Date.parse(datetime))) {
102			d = new Date(datetime)
103			pad = function (s) {return s < 10 ? '0' + s : s}
104			mon = function (m) {return ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][m]}
105			datetime = datetime_format
106					.replace('%Y', d.getFullYear())
107					.replace('%m', pad(d.getMonth()+1))
108					.replace('%d', pad(d.getDate()))
109					.replace('%H', pad(d.getHours()))
110					.replace('%M', pad(d.getMinutes()))
111					.replace('%S', pad(d.getSeconds()))
112					.replace('%b', mon(d.getMonth()))
113		}
114
115		tr = tbody.add('tr')
116		tr.add('td').add('a').attr('class', 'octicon ' + css).attr('href', filename).text(displayname)
117		tr.add('td').text(datetime)
118		tr.add('td').text(size)
119
120		if (/\.(md)$/.test(filename)) {
121			tr.add('td').add('input').attr('type', 'button').attr('value','preview').attr('onclick', 'onPreview("' + filename +'")').attr('id', filename)
122		} else {
123			tr.add('td')
124		}
125	}
126
127	var readme = '', footer = ''
128	insert('../', '', '-')
129	for (var i in bodylines) {
130		if (m = /\s*<a href="(.+?)">(.+?)<\/a>\s+(\S+)\s+(\S+)\s+(\S+)\s*/.exec(bodylines[i])) {
131			filename = m[1]
132			datetime = m[3] + ' ' + m[4]
133			size = m[5]
134			insert(filename, datetime, size)
135			switch (filename.toLowerCase()) {
136			case 'readme.md':
137				readme = filename
138				break
139			case 'footer.js':
140				footer = filename
141				break
142			}
143		}
144	}
145
146	document.documentElement.lang = navigator.language
147	document.body.appendChild(div.element)
148
149	if (enable_readme_md && readme !== '') {
150		tbody = div.add('table').add('tbody');
151		tbody.add('tr').add('th').attr('class', 'octicon octicon-book').text(readme)
152		tbody.add('tr').add('td').add('div').attr('id', 'readme').attr('class', 'markdown-body')
153		xhr = new XMLHttpRequest()
154		xhr.open('GET', location.pathname.replace(/[^/]+$/, '')+readme, true)
155		xhr.onload = function() {
156			if (xhr.status < 200 && xhr.status >= 400)
157				return
158			wait = function (name, callback) {
159				var interval = 10; // ms
160				window.setTimeout(function() {
161					if (window[name]) {
162						callback(window[name])
163					} else {
164						window.setTimeout(arguments.callee, interval)
165					}
166				}, interval)
167			}
168			wait('marked', function() {
169				document.getElementById("readme").innerHTML = marked.parse(xhr.responseText)
170			})
171		}
172		xhr.send()
173
174		div.add('script').attr('src', marked_js)
175		div.add('link').attr('rel', 'stylesheet').attr('href', github_markdown_css)
176	}
177
178	if (enable_footer_js && footer !== '') {
179		div.add('script').attr('src', footer)
180	}
181}()
182
183function onPreview(filename) {
184	myWindow=window.open('','_blank','');
185	myWindow.document.write("<div id='markdown'></div");
186	myWindow.document.title=filename 
187	ele = myWindow.document.getElementById("markdown")
188	
189	xhr = new XMLHttpRequest()
190	xhr.open('GET', location.pathname.replace(/[^/]+$/, '')+filename, true)
191	xhr.onload = function() {
192		if (xhr.status < 200 && xhr.status >= 400)
193			return
194		wait = function (name, callback) {
195			var interval = 10; // ms
196			window.setTimeout(function() {
197				if (window[name]) {
198					callback(window[name])
199				} else {
200					window.setTimeout(arguments.callee, interval)
201				}
202			}, interval)
203		}
204		wait('marked', function() {
205			myWindow.document.getElementById("markdown").innerHTML = marked.parse(xhr.responseText)
206		})
207	}
208	xhr.send()
209	div.add('script').attr('src', marked_js)
210	div.add('link').attr('rel', 'stylesheet').attr('href', github_markdown_css)
211	myWindow.focus();
212}
213
214function sortby(index) {
215	rows = document.getElementsByClassName('table-hover')[0].rows
216	link = rows[0].getElementsByTagName('a')[index]
217	arrow = link.className == 'octicon arrow-down' ? 1 : -1
218	link.className = 'octicon arrow-' + (arrow == 1 ? 'up' : 'down');
219	[].slice.call(rows).slice(2).map(function (e, i) {
220		type = e.getElementsByTagName('a')[0].className == 'octicon file-directory' ? 0 : 1
221		text = e.getElementsByTagName('td')[index].innerText
222		if (index === 0) {
223			value = text
224		} else if (index === 1) {
225			value = new Date(text).getTime()
226		} else if (index === 2) {
227			m = {'G':1024*1024*1024, 'M':1024*1024, 'K':1024}
228			value = parseInt(text || 0) * (m[text[text.search(/[KMG]B?$/)]] || 1)
229		}
230		return {type: type, value: value, index: i, html: e.innerHTML}
231	}).sort(function (a, b) {
232		if (a.type != b.type)
233			return a.type - b.type
234		if (a.value != b.value)
235			return a.value < b.value ? -arrow : arrow
236		return a.index < b.index ? -arrow : arrow
237	}).forEach(function (e, i) {
238		rows[2+i].innerHTML = e.html
239	})
240}
241</script>
242
243<style>
244body {
245	margin: 0;
246	font-family: "ubuntu", "Tahoma", "Microsoft YaHei", Arial, Serif;
247}
248.container {
249	padding-right: 15px;
250	padding-left: 15px;
251	margin-right: auto;
252	margin-left: auto;
253}
254@media (min-width: 768px) {
255	.container {
256		max-width: 750px;
257	}
258}
259@media (min-width: 992px) {
260	.container {
261		max-width: 970px;
262	}
263}
264@media (min-width: 1200px) {
265	.container {
266		max-width: 1170px;
267	}
268}
269table {
270	width: 100%;
271	max-width: 100%;
272	margin-bottom: 20px;
273	border: 1px solid #ddd;
274	padding: 0;
275	border-collapse: collapse;
276}
277table th {
278	font-size: 14px;
279}
280table tr {
281	border: 1px solid #ddd;
282	padding: 5px;
283}
284table tr:nth-child(odd) {
285	background: #f9f9f9
286}
287table th, table td {
288	border: 1px solid #ddd;
289	font-size: 14px;
290	line-height: 20px;
291	padding: 3px;
292	text-align: left;
293}
294a {
295	color: #337ab7;
296	text-decoration: none;
297}
298a:hover, a:focus {
299	color: #2a6496;
300	text-decoration: underline;
301}
302table.table-hover > tbody > tr:hover > td,
303table.table-hover > tbody > tr:hover > th {
304	background-color: #f5f5f5;
305}
306.markdown-body {
307	float: left;
308	font-family: "ubuntu", "Tahoma", "Microsoft YaHei", Arial, Serif;
309}
310/* octicons */
311.octicon {
312	background-position: center left;
313	background-repeat: no-repeat;
314	padding-left: 16px;
315}
316.file {
317	background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='16' viewBox='0 0 12 16'%3E%3Cpath d='M6 5L2 5 2 4 6 4 6 5 6 5ZM2 8L9 8 9 7 2 7 2 8 2 8ZM2 10L9 10 9 9 2 9 2 10 2 10ZM2 12L9 12 9 11 2 11 2 12 2 12ZM12 4.5L12 14C12 14.6 11.6 15 11 15L1 15C0.5 15 0 14.6 0 14L0 2C0 1.5 0.5 1 1 1L8.5 1 12 4.5 12 4.5ZM11 5L8 2 1 2 1 14 11 14 11 5 11 5Z' fill='%237D94AE'/%3E%3C/svg%3E");
318}
319.file-directory {
320	background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='16' viewBox='0 0 14 16'%3E%3Cpath d='M13 4L7 4 7 3C7 2.3 6.7 2 6 2L1 2C0.5 2 0 2.5 0 3L0 13C0 13.6 0.5 14 1 14L13 14C13.6 14 14 13.6 14 13L14 5C14 4.5 13.6 4 13 4L13 4ZM6 4L1 4 1 3 6 3 6 4 6 4Z' fill='%237D94AE'/%3E%3C/svg%3E");
321}
322.file-zip {
323	background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='16' viewBox='0 0 12 16'%3E%3Cpath d='M8.5 1L1 1C0.4 1 0 1.4 0 2L0 14C0 14.6 0.4 15 1 15L11 15C11.6 15 12 14.6 12 14L12 4.5 8.5 1ZM11 14L1 14 1 2 4 2 4 3 5 3 5 2 8 2 11 5 11 14 11 14ZM5 4L5 3 6 3 6 4 5 4 5 4ZM4 4L5 4 5 5 4 5 4 4 4 4ZM5 6L5 5 6 5 6 6 5 6 5 6ZM4 6L5 6 5 7 4 7 4 6 4 6ZM5 8L5 7 6 7 6 8 5 8 5 8ZM4 9.3C3.4 9.6 3 10.3 3 11L3 12 7 12 7 11C7 9.9 6.1 9 5 9L5 8 4 8 4 9.3 4 9.3ZM6 10L6 11 4 11 4 10 6 10 6 10Z' fill='%237D94AE'/%3E%3C/svg%3E");
324}
325.file-code {
326	background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='16' viewBox='0 0 12 16'%3E%3Cpath d='M8.5,1 L1,1 C0.45,1 0,1.45 0,2 L0,14 C0,14.55 0.45,15 1,15 L11,15 C11.55,15 12,14.55 12,14 L12,4.5 L8.5,1 L8.5,1 Z M11,14 L1,14 L1,2 L8,2 L11,5 L11,14 L11,14 Z M5,6.98 L3.5,8.5 L5,10 L4.5,11 L2,8.5 L4.5,6 L5,6.98 L5,6.98 Z M7.5,6 L10,8.5 L7.5,11 L7,10.02 L8.5,8.5 L7,7 L7.5,6 L7.5,6 Z' fill='%237D94AE' /%3E%3C/svg%3E");
327}
328.file-media {
329	background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='16' viewBox='0 0 12 16'%3E%3Cpath d='M6 5L8 5 8 7 6 7 6 5 6 5ZM12 4.5L12 14C12 14.6 11.6 15 11 15L1 15C0.5 15 0 14.6 0 14L0 2C0 1.5 0.5 1 1 1L8.5 1 12 4.5 12 4.5ZM11 5L8 2 1 2 1 13 4 8 6 12 8 10 11 13 11 5 11 5Z' fill='%237D94AE'/%3E%3C/svg%3E");
330}
331.device-camera-video {
332	background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3E%3Cpath d='M15.2,2.09 L10,5.72 L10,3 C10,2.45 9.55,2 9,2 L1,2 C0.45,2 0,2.45 0,3 L0,12 C0,12.55 0.45,13 1,13 L9,13 C9.55,13 10,12.55 10,12 L10,9.28 L15.2,12.91 C15.53,13.14 16,12.91 16,12.5 L16,2.5 C16,2.09 15.53,1.86 15.2,2.09 L15.2,2.09 Z' fill='%237D94AE' /%3E%3C/svg%3E");
333}
334.octicon-book {
335	padding-left: 20px;
336	background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'%3E%3Cpath d='M3,5 L7,5 L7,6 L3,6 L3,5 L3,5 Z M3,8 L7,8 L7,7 L3,7 L3,8 L3,8 Z M3,10 L7,10 L7,9 L3,9 L3,10 L3,10 Z M14,5 L10,5 L10,6 L14,6 L14,5 L14,5 Z M14,7 L10,7 L10,8 L14,8 L14,7 L14,7 Z M14,9 L10,9 L10,10 L14,10 L14,9 L14,9 Z M16,3 L16,12 C16,12.55 15.55,13 15,13 L9.5,13 L8.5,14 L7.5,13 L2,13 C1.45,13 1,12.55 1,12 L1,3 C1,2.45 1.45,2 2,2 L7.5,2 L8.5,3 L9.5,2 L15,2 C15.55,2 16,2.45 16,3 L16,3 Z M8,3.5 L7.5,3 L2,3 L2,12 L8,12 L8,3.5 L8,3.5 Z M15,3 L9.5,3 L9,3.5 L9,12 L15,12 L15,3 L15,3 Z' /%3E%3C/svg%3E");
337}
338.arrow-down {
339	font-weight: bold;
340	text-decoration: none !important;
341	background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='16' viewBox='0 0 10 16'%3E%3Cpolygon id='Shape' points='7 7 7 3 3 3 3 7 0 7 5 13 10 7'%3E%3C/polygon%3E%3C/svg%3E");
342}
343.arrow-up {
344	font-weight: bold;
345	text-decoration: none !important;
346	background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='16' viewBox='0 0 10 16'%3E%3Cpolygon id='Shape' points='5 3 0 9 3 9 3 13 7 13 7 9 10 9'%3E%3C/polygon%3E%3C/svg%3E");
347}
348</style>

参考: https://1kb.day/posts/nginx_autoindex.html https://akawa.ink/2020/05/23/make-nginx-autoindex-page-beauty