1

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!

ayublin
  • 113
  • 1
  • 5

1 Answers1

3

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

krisFR
  • 12,830
  • 3
  • 31
  • 40
  • 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 06:39
  • Late answer: Yes, to omit the last slash you just have to move the bracket a bit forward like: ~(?^/[a-zA-Z0-9]+)[/] – Matthias Kleine Oct 26 '16 at 20:12