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!


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

  • 1
    Many thanks! This Works! Wish I could up vote a hundred times! :) 2 little questions, is that possible to omit the last /? or is it possible to escape nginx variable in a string? e.g: {$topdir}/sub/index.php? – ayublin Apr 16 '14 at 6:39
  • Late answer: Yes, to omit the last slash you just have to move the bracket a bit forward like: ~(?<captured_topdir>^/[a-zA-Z0-9]+)[/] – Matthias Kleine Oct 26 '16 at 20:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.