Nginx 目录浏览功能显示的日期格式设置为数字

在 Nginx 中,默认的目录浏览功能显示的日期格式包含英文月份,若想将其显示为数字月份,需要对 Nginx 的 autoindex 模块输出进行自定义处理。

由于 Nginx 本身没有直接配置将日期格式化为数字月份的选项,所以可以借助 Lua 脚本结合 ngx_http_lua_module 模块来实现这个需求。

步骤如下

  1. 确认 ngx_http_lua_module 模块已安装 首先要保证 Nginx 已经安装了 ngx_http_lua_module 模块。

你可以通过以下命令查看 Nginx 编译时的配置参数:

Lua 复制代码
nginx -V 2>&1 | grep lua

若输出包含 lua 相关信息,说明该模块已安装;

若没有,你需要重新编译 Nginx 并添加 --with-http_lua_module 选项。

使用豆包问:

已经安装的nginx,如何重新编译 Nginx 并添加 --with-http_lua_module 选项。

  1. 创建 Lua 脚本 在合适的目录(例如 /etc/nginx/lua)下创建一个 Lua 脚本,如 format_autoindex.lua,内容如下:
Lua 复制代码
-- 读取原始的 autoindex 输出
local html = ngx.arg[1]
-- 使用正则表达式替换日期格式
html = string.gsub(html, "(%d+)-(%a+)-(%d+)", function(day, month, year)
    local months = {
        Jan = "01", Feb = "02", Mar = "03", Apr = "04",
        May = "05", Jun = "06", Jul = "07", Aug = "08",
        Sep = "09", Oct = "10", Nov = "11", Dec = "12"
    }
    return string.format("%s-%s-%s", year, months[month], day)
end)
-- 输出处理后的 HTML
ngx.arg[1] = html
  1. 修改 Nginx 配置文件 在 Nginx 配置文件里添加对 Lua 脚本的调用,示例如下:
Lua 复制代码
server {
    listen 80;
    server_name your_domain_or_ip;

    location /gp/ {
        autoindex on;
        # 在输出之前执行 Lua 脚本
        header_filter_by_lua_file /etc/nginx/lua/format_autoindex.lua;
    }
}

要把 your_domain_or_ip 替换为实际的域名或者 IP 地址。

  1. 检查并重新加载 Nginx 配置 执行以下命令检查配置文件语法是否正确:
Lua 复制代码
nginx -t

若语法检查通过,重新加载 Nginx 配置:

Lua 复制代码
systemctl reload nginx
相关推荐
可观测性用观测云3 小时前
云原生网关 Ingress-Nginx 链路追踪实战:OpenTelemetry 采集与观测云集成方案
nginx·kubernetes
甲鱼9297 小时前
MySQL 实战手记:日志管理与主从复制搭建全指南
运维
闲云一鹤2 天前
nginx 快速入门教程 - 写给前端的你
前端·nginx·前端工程化
碳基沙盒2 天前
OpenClaw 多 Agent 配置实战指南
运维
金銀銅鐵3 天前
浅解 JUnit 4 第十一篇:@Before 注解和 @After 注解如何发挥作用?
junit·单元测试
金銀銅鐵4 天前
浅解 JUnit 4 第十篇:方法上的 @Ignore 注解
junit·单元测试
蝎子莱莱爱打怪5 天前
Centos7中一键安装K8s集群以及Rancher安装记录
运维·后端·kubernetes
何中应5 天前
Nginx转发请求错误
前端·后端·nginx
DianSan_ERP6 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线
大数据·运维·网络·人工智能·git·servlet