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?
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.
Source: Stackoverflow.com