根据您的需求,我将提供一个解决方案来优化 Nginx 自动索引页面的对齐问题,使其看起来更像一个整齐的表格。
解决方案
由于 add_after_body
指令在您的 Nginx 中不可用,我们可以通过修改 Nginx 配置来添加自定义 CSS 样式,从而改善目录列表的对齐和外观。
修改 Nginx 配置文件
首先,请修改您的 /etc/nginx/sites-enabled/files.conf
文件:
server {
listen 8800;
server_name localhost;
charset utf-8;
root /volume1/ding_share/nginx-files;
index index.html index.htm;
# 自定义 CSS 样式
location = /autoindex.css {
add_header Content-Type text/css;
return 200 '
body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; margin: 20px; }
h1 { color: #333; border-bottom: 1px solid #eee; padding-bottom: 10px; }
table { width: 100%; border-collapse: collapse; }
th { text-align: left; padding: 8px; background-color: #f5f5f5; border-bottom: 2px solid #ddd; }
td { padding: 8px; border-bottom: 1px solid #eee; vertical-align: top; }
tr:hover { background-color: #f9f9f9; }
a { text-decoration: none; color: #337ab7; }
a:hover { text-decoration: underline; }
.size { text-align: right; font-family: monospace; }
.date { white-space: nowrap; }
';
}
# 允许目录索引
location / {
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
# 添加自定义样式
add_before_body /.autoindex-header.html;
# 设置自定义样式表
add_header Content-Style-Type "text/css";
add_header Link '</autoindex.css>; rel=stylesheet; type=text/css';
}
}
创建自定义头部文件
创建 /.autoindex-header.html
文件(与您的配置文件同一目录):
<style>
body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; margin: 20px; }
h1 { color: #333; border-bottom: 1px solid #eee; padding-bottom: 10px; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th { text-align: left; padding: 12px; background-color: #f5f5f5; border-bottom: 2px solid #ddd; font-weight: bold; }
td { padding: 10px; border-bottom: 1px solid #eee; vertical-align: top; }
tr:hover { background-color: #f9f9f9; }
a { text-decoration: none; color: #337ab7; font-weight: 500; }
a:hover { text-decoration: underline; }
.size { text-align: right; font-family: monospace; width: 120px; }
.date { white-space: nowrap; width: 180px; }
.name { word-break: break-all; }
</style>
替代方案:使用 JavaScript 增强
如果上述方法仍然不工作,您可以创建一个简单的 JavaScript 解决方案。创建一个名为 enhance-listing.js
的文件:
// 当页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
// 获取表格元素
const table = document.querySelector('table');
if (!table) return;
// 添加CSS类到表格
table.classList.add('enhanced-table');
// 获取所有行
const rows = table.querySelectorAll('tr');
// 处理每一行
rows.forEach((row, index) => {
// 跳过表头行
if (index === 0) return;
// 获取所有