Search code examples
nginxlocationnginx-config

Nginx: choose alias depending on a query string parameter


I want my Nginx server to give away files depending on a query string parameter. I have directories for debug files and release files and want to distribute them according to a parameter value:

location /files/ {
    if ( $arg_isDebug = "true" )
    {
        alias "C:/DebugFiles/";
    }
    if ( $!arg_isDebug != "true" )
    {
        alias "C:/ReleaseFiles/Release/";
    }
}

But it gives me an error

"alias" directive is not allowed here ...

Why can't I write it inside an 'if' statement and is there a workaround for this?


Solution

  • Why can't I write it inside an 'if' statement

    The documentation states that alias can only be used in a location context.

    is there a workaround for this?

    Use a map directive.

    For example:

    map $arg_isDebug $alias {
    default   "C:/ReleaseFiles/Release/";
    true      "C:/DebugFiles/";
    }
    
    server {
        ...
        location ^~ /files/ {
            alias $alias;
        }
    }
    

    The map block is declared outside of the server block. Both the location value and alias value should end with / or neither end with /. You may want to use the ^~ operator to avoid a potential conflict with any regular expression locations within the same server block.