Home > database >  Dynamic location block variable to string
Dynamic location block variable to string

Time:11-08

I am trying to generate a single nginx location block that dymically changes depending on a captured matching location

location ~*\/(\w )/archive {   
  fancyindex_footer "/fancyindex/footer-{$1}.html";
}

So if the location is /something/archive I want the string to say /fancyindex/footer-something.html

It's a simple request but I'm struggling to get it done or even being able to debug

CodePudding user response:

Well, I've made some testing. Indeed, the fancyindex_footer directive can't interpolate variables from its parameter. Most likely the reason is that it is based on add_after_body directive from the ngx_http_addition_module, and that one can't do it too. However using a named capture group the following workaround should work:

location ~* /(?<idx>\w )/archive {
    # by using a named capture group, we make our prefix to be captured with the
    # '$idx' variable rather than '$1' one, to be used later in the other location
    add_after_body /fancyindex/;
    # '/fancyindex/` string treated as a subrequest URI
}

location /fancyindex/ {
    # don't allow external access, use only as internal location
    internal;
    # use the full path to the 'fancyindex' folder as a root here
    root /full/path/to/fancyindex;
    # rewrite any URI to the '/footer-$idx.html' and serve it as a footer file
    rewrite ^ /footer-$idx.html break;
}

If I misunderstood your question and you just want to append a /fancyindex/footer-something.html string to your output instead of /fancyindex/footer-something.html file contents, change the internal location to

location /fancyindex/ {
    internal;
    return 200 "/fancyindex/footer-$idx.html";
}
  • Related