Reuse configuration statements for domains in nginx.conf

you can do:

 server_name one.example.org two.example.org;

if both are exactly identical except for the domainname

if you have just similar locationblocks you can move those locations to a separate file and then do an

include /etc/nginx/your-filename; 

to easily use it in each serverblock


This is a good example to use nginx Map module. http://wiki.nginx.org/HttpMapModule

Following is what I tried. It works in my devbox. Note

  1. map directive can only be put in the http block.
  2. performance penalty of declaring a map directive is negligible (see above link)
  3. you can have freedom to have different root folder, or port number, etc.

    map $subdomain $root_folder {
      one  /path/to/one;
      two  /path/to/two;
    }
    
    map $subdomain $port_number {
      one 9000;
      two 9100;
    }
    
    server {
      listen  80;
      server_name  ~^(?P<subdomain>.+?)\.mydomain\.com$;
      root  $root_folder;
    
       location ~ \.php$ {
        try_files       $uri =404;
        fastcgi_pass    127.0.0.1:$port_number;
        fastcgi_index   index.php;
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include         fastcgi_params;
      }
    }
    

Tags:

Nginx