【问题标题】:Rewrite by lua : Match host由 lua 重写:匹配主机
【发布时间】:2019-05-29 20:28:30
【问题描述】:

我有这个 lua 脚本,可以根据用户的浏览器语言重定向用户。

location = / {
    rewrite_by_lua '
        for lang in (ngx.var.http_accept_language .. ","):gmatch("([^,]*),") do
            if string.sub(lang, 0, 2) == "en" then
                ngx.redirect("/en/index.html")
            end
            if string.sub(lang, 0, 2) == "nl" then
                ngx.redirect("/nl/index.html")
            end
            if string.sub(lang, 0, 2) == "de" then
                ngx.redirect("/de/index.html")
            end
        end
        ngx.redirect("/en/index.html")
    ';
}

我只想匹配以mysite.org 结尾的网址 知道如何添加条件吗?

结果应该是这样的:

if string.sub(lang, 0, 2) == "nl" and host == "mysite.org" then
                    ngx.redirect("/nl")
                end

【问题讨论】:

  • 与您的主要问题无关,但在普通 Lua 中,索引是基于 1 的,因此您可能指的是 string.sub(lang,1,2),也可以写为 lang:sub(1,2)。但我不知道 nginx 是否有一个从零开始索引的修改过的 Lua。

标签: nginx lua


【解决方案1】:

如果没有您确切输入的完整详细信息,我认为以下应该可行:

location = / {
    rewrite_by_lua '
        for lang in (ngx.var.http_accept_language .. ","):gmatch("([^,]*),") do
          lang = lang:sub(1, 2)
          if host:match("mysite%.org$") then
            if lang == "en" then ngx.redirect("/en/index.html")
            elseif lang == "nl" then ngx.redirect("/nl/index.html")
            elseif lang == "de" then ngx.redirect("/de/index.html")
            end
          end
        end
        ngx.redirect("/en/index.html")
    ';
}

还要注意使用elseif 来缩短代码。另一方面,可以省略对“en”语言的显式检查,因为它是默认的失败案例。

【讨论】:

    猜你喜欢
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 1970-01-01
    • 2019-10-25
    相关资源
    最近更新 更多