You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx如何基于环境变量通过Lua定义不同404错误页面

基于环境变量动态选择404错误页面的Lua实现方案

你可以通过两种方式实现这个需求,以下是具体配置示例:

方法一:提前定义变量供error_page使用

利用set_by_lua_block预定义存储404页面路径的变量,再让error_page指令引用该变量,和你现有获取环境变量的逻辑保持一致:

server {
    # 提前定义动态404页面路径变量
    set_by_lua_block $custom_404_page {
        local condition = os.getenv("condition")
        # 根据环境变量值判断,可按需调整判断逻辑(比如判断是否为"true"、非空等)
        if condition and condition ~= "" and condition:lower() == "true" then
            return "/error-pages/404.html"
        else
            return "/error-pages/404-2.html"
        end
    }

    # 引用预定义的变量作为404页面路径
    error_page 404 $custom_404_page;

    # 确保错误页面所在路径能被Nginx正常访问
    location /error-pages/ {
        root /path/to/your/webroot; # 替换为实际的网站根目录路径
        expires 1h;
    }

    # 其他server配置...
}

方法二:在错误处理Location中用Lua动态跳转

通过error_page将404请求转发到专门的处理Location,在该Location内用Lua逻辑选择页面:

server {
    error_page 404 @handle_404;

    # 处理404请求的Location
    location @handle_404 {
        content_by_lua_block {
            local condition = os.getenv("condition")
            local target_page
            # 自定义判断逻辑
            if condition and condition:lower() == "true" then
                target_page = "/error-pages/404.html"
            else
                target_page = "/error-pages/404-2.html"
            end
            # 跳转到目标页面(也可直接读取文件返回,用ngx.send_file)
            ngx.redirect(target_page)
        }
    }

    # 确保错误页面可访问
    location /error-pages/ {
        root /path/to/your/webroot;
    }

    # 其他server配置...
}

注意事项

  • 确保ngx_http_lua_module已正确安装并启用(你之前能正常使用set_by_lua_block,此条件已满足)
  • 环境变量condition的判断逻辑可根据实际值调整(比如你的环境变量是prod/dev,则修改判断条件为condition == "prod")
  • 错误页面的路径需和Nginx配置的root或alias对应,确保文件存在且Nginx有权限读取

内容的提问来源于stack exchange,提问作者Ziko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 12:55:06