Nginx Extract Top Directory Name From Request URI

nginxregexrewriteweb-server

I am in the need of being able to use top directory from the $request_uri, for example:

/dir/sub/slug -> /dir

I read the answer of this question:
How to extract Only the file name from the request 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;
}

And it seems to be close with what I need, how does that works? is it possible to be modified to get the top directory instead? Thanks!

Best Answer

I think that something like this should do the trick.

In my sample, to test what was returned, i added the variable $topdir into the 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 should return /dir/

  • http://mydomain.com or http://mydomain.com/page.html should return nothing

Related Topic