使用lua重写:匹配主机

我有这个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结尾的url 有什么办法可以添加这个条件吗?

结果应该像这样:

if string.sub(lang, 0, 2) == "nl" and host == "mysite.org" then
                    ngx.redirect("/nl")
                end
点赞
用户3735873
用户3735873
我没有完整的输入详情,但是我认为下面的代码可以工作:

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' 语言的显式检查,因为这是默认的落空情况。

2019-05-29 12:16:09