Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse configuration statements for domains in nginx.conf

Tags:

nginx

Let's say I have a nginx configuration set up for a domain like this:

server {

  root /path/to/one;
  server_name one.example.org;

  location ~ \.php$ {
    try_files       $uri =404;
    fastcgi_pass    127.0.0.1:9000;
    fastcgi_index   index.php;
    fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include         fastcgi_params;
  }

}

Now, if I want to add another domain with different content, is there a way I can re-use equivalent statements from the previous domain, or do I have to duplicate everything for every new domain I want to support?

server {

  root /path/to/two; # different
  server_name two.example.org; # different

  location ~ \.php$ {
    try_files       $uri =404;
    fastcgi_pass    127.0.0.1:9000;
    fastcgi_index   index.php;
    fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include         fastcgi_params;
  }

}

I tried moving the location directive outside the server closure, but obviously things don't work like that because I got an error "location directive is not allowed here" when restarting nginx.

like image 653
forthrin Avatar asked Mar 29 '13 14:03

forthrin


2 Answers

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;
      }
    }
    
like image 123
Chuan Ma Avatar answered Oct 05 '22 19:10

Chuan Ma


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

like image 31
cobaco Avatar answered Oct 05 '22 17:10

cobaco