Using variables in Nginx location rules

前端 未结 4 515
自闭症患者
自闭症患者 2020-12-12 17:54

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         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-12 18:48

    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)
    

提交回复
热议问题