[variables] Using variables in Nginx location rules

In Nginx, I'm trying to define a variable which allows me to configure a sub-folder for all my location blocks. I did this:

set $folder '/test';

location $folder/ {
   [...]
}

location $folder/something {
   [...]
}

Unfortunately, this doesn't seem to work. While Nginx doesn't complain about the syntax, it returns a 404 when requesting /test/. If I write the folder in explicitly, it works. So how can I use variables in location blocks?

This question is related to variables nginx webserver

The answer is


A modified python version of @danack's PHP generate script. It generates all files & folders that live inside of build/ to the parent directory, replacing all {{placeholder}} matches. You need to cd into build/ before running the script.

File structure

build/
-- (files/folders you want to generate)
-- build.py

sites-available/...
sites-enabled/...
nginx.conf
...

build.py

import os, re

# Configurations
target = os.path.join('.', '..')
variables = {
  'placeholder': 'your replacement here'
}


# Loop files
def loop(cb, subdir=''):
  dir = os.path.join('.', subdir);

  for name in os.listdir(dir):
    file = os.path.join(dir, name)
    newsubdir = os.path.join(subdir, name)

    if name == 'build.py': continue
    if os.path.isdir(file): loop(cb, newsubdir)
    else: cb(subdir, name)


# Update file
def replacer(subdir, name):
  dir  = os.path.join(target, subdir)
  file = os.path.join(dir, name)
  oldfile = os.path.join('.', subdir, name)

  with open(oldfile, "r") as fin:
    data = fin.read()

  for key, replacement in variables.iteritems():
    data = re.sub(r"{{\s*" + key + "\s*}}", replacement, data)

  if not os.path.exists(dir):
    os.makedirs(dir)

  with open(file, "w") as fout:
    fout.write(data)


# Start variable replacements.
loop(replacer)

You could do the opposite of what you proposed.

location (/test)/ {
   set $folder $1;
}

location (/test_/something {
   set $folder $1;
}

This is many years late but since I found the solution I'll post it here. By using maps it is possible to do what was asked:

map $http_host $variable_name {
    hostnames;

    default       /ap/;
    example.com   /api/;
    *.example.org /whatever/;
}

server {
    location $variable_name/test {
        proxy_pass $auth_proxy;
    }
}

If you need to share the same endpoint across multiple servers, you can also reduce the cost by simply defaulting the value:

map "" $variable_name {
    default       /test/;
}

Map can be used to initialise a variable based on the content of a string and can be used inside http scope allowing variables to be global and sharable across servers.


Examples related to variables

When to create variables (memory management) How to print a Groovy variable in Jenkins? What does ${} (dollar sign and curly braces) mean in a string in Javascript? How to access global variables How to initialize a variable of date type in java? How to define a variable in a Dockerfile? Why does foo = filter(...) return a <filter object>, not a list? How can I pass variable to ansible playbook in the command line? How do I use this JavaScript variable in HTML? Static vs class functions/variables in Swift classes?

Examples related to nginx

Kubernetes service external ip pending nginx: [emerg] "server" directive is not allowed here Disable nginx cache for JavaScript files Nginx upstream prematurely closed connection while reading response header from upstream, for large requests Nginx: Job for nginx.service failed because the control process exited How can I have same rule for two locations in NGINX config? How to verify if nginx is running or not? Find nginx version? Docker Networking - nginx: [emerg] host not found in upstream How do I rewrite URLs in a proxy response in NGINX

Examples related to webserver

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests Apache Server (xampp) doesn't run on Windows 10 (Port 80) What is the difference between HTTP 1.1 and HTTP 2.0? Reload nginx configuration The program can't start because MSVCR110.dll is missing from your computer XAMPP Object not found error Amazon AWS Filezilla transfer permission denied how to configuring a xampp web server for different root directory How to open a web server port on EC2 instance Minimal web server using netcat