NGINX / Lua - 动态根文件夹/URI 重写

问题描述 投票:0回答:1

我正在使用 Lua 运行 NGINX 服务器(通过 OpenResty)。

我想实现一个非常简单的事情:

  1. 如果用户从文件夹
    /
    访问
    startpage
  2. 服务
  3. 如果用户访问任何其他路径,例如
    /foo
    ,则从文件夹
    /html/foo
  4. 提供服务

我尝试了很多方法,但似乎没有任何效果。我无法通过

ngx.var.document_root = "/startpage"
更改根文件夹 - 我收到错误。

然后我尝试了这个脚本,但我没有对网址进行内部重写,而是重定向到“/startpage”,因此用户可以在浏览器地址栏中看到“/startpage”,这是我不想要的。

-- Check if the script has already been executed - without this check, this script is called recursively
if rewritten ~= true then
    rewritten = true

    -- Root ("/") was called, set correct startpage
    if ngx.var.uri == "/" then
        ngx.req.set_uri("/startpage")
    -- Otherwise, set correct path to the called resource
    else
        ngx.req.set_uri("/html"..ngx.var.uri)
    end
end

如果有人能指出我正确的方向,我将非常感激。

具体目标是什么?

如果用户调用root

/
:

  1. 如果用户已登录:从
    /startpage/user
  2. 提供文件
  3. 如果用户已登录:从
    /startpage/guest
  4. 提供文件

Else(用户调用任何其他 URL):

  1. 示例:用户调用
    /foo
    :从
    /html/foo
  2. 提供文件
  3. 示例:用户调用
    /foo/bar/baz
    :从
    /html/foo/bar/baz
  4. 提供文件

身份验证逻辑全部正常工作,因此我知道用户是否已登录。我只需要设置动态提供文件的根文件夹。

nginx lua url-rewriting
1个回答
0
投票

你不需要 Lua 来实现这一点,

location
指令就足够了:

location = / {
    alias ./startpage/;
    try_files index.html =404;
}

location / {
    root ./html/;
}

URL → 文件系统路径:

  • / → /startpage/index.html
  • /foo/→/html/foo/index.html
  • /foo/img.jpg → /html/foo/img.jpg
  • /bar/text.txt → /html/bar/text.txt
© www.soinside.com 2019 - 2024. All rights reserved.