Nginx从请求URI中提取顶级目录名称

我需要能够使用$request_uri顶级目录,例如:

/dir/sub/slug – > /dir

我读了这个问题的答案: 如何从请求中提取只有文件名uri

 # Gets the basename of the original request map $request_uri $request_basename { ~/(?<captured_request_basename>[^/?]*)(?:\?|$) $captured_request_basename; } # Gets the basename of the current uri map $uri $basename { ~/(?<captured_basename>[^/]*)$ $captured_basename; } 

它似乎与我所需要的接近,这是如何工作的? 是否有可能被修改,以获得顶部目录呢? 谢谢!

我认为,这样的事情应该做的伎俩。

在我的示例中,为了testing返回的内容,我将variables$topdir添加到Header中。

 map $request_uri $topdir { ~(?<captured_topdir>^/[a-zA-Z0-9]+[/]) $captured_topdir; } server { listen 80; root /var/www; index index.html; location / { add_header X-Top-Dir $topdir; } } 
  • http://mydomain.com/dir/sub/slug/page.html应该返回/dir/

  • http://mydomain.comhttp://mydomain.com/page.html应该不会返回任何内容