11

Is there any way to reduce construction like:

server { 
  server_name regular_site; 
  location /api/ { 
     proxy_pass 127.0.0.1:5000;
  } 
  location / { 
     proxy_pass 127.0.0.1:3000;
  } 
} 

server { 
  server_name mobile_site; 
  location /api/ { 
     proxy_pass 127.0.0.1:5000;
  } 
  location / { 
     proxy_pass 127.0.0.1:3001;
  } 
} 

to

server api { 
  location /api/ { 
     proxy_pass 127.0.0.1:5000;
  } 
}

server extends api { 
  server_name regular_site;
  location / { 
     proxy_pass 127.0.0.1:3000;
  } 
} 

server extends api { 
  server_name mobile_site;
  location / { 
     proxy_pass 127.0.0.1:3001;
  } 
} 

Any other advices for getting rid of api section are welcome.

Nikolay Fominyh
  • 286
  • 4
  • 11
  • [Please take a moment to read our FAQ.](http://serverfault.com/faq) Your question appears off-topic for this site to me. – HopelessN00b Oct 08 '12 at 02:04
  • @HopelessN00b, yes, looks like it's offtopic. But here we have 3000 questions about nginx, which is strange in this case. I'm sure, that this question is not for stackoverflow. – Nikolay Fominyh Oct 08 '12 at 08:51

1 Answers1

15

You could do it quite easily with a include statement.

In /etc/nginx/conf/api_defaults.conf:

location /api/ { 
  proxy_pass 127.0.0.1:5000;
}    

Then in your main vhost config.

/etc/nginx/sites-enabled/my_new_api.conf

server my_new_api {  
  server_name mobile_site;

  include "/etc/nginx/conf/api_defaults.conf";

  location / { 
    proxy_pass 127.0.0.1:3001;
  }         
}
Ben Lessani
  • 5,244
  • 17
  • 37
  • That's what I thought as well, in other words location blocks are not inherited to server blocks. This is unlike how Apache does it, where you can have locations defined outside of virtualhosts, that are inherited by all virtualhosts. With Nginx you must explicitly include the common configs, in each server block. – J. M. Becker Nov 20 '14 at 15:23
  • I'm following this example for my case, but I get an error saying `nginx: [emerg] "location" directive is not allowed here in /etc/nginx/conf.d/shared.conf`. (In my case shared.conf is the included file.) Are you only allowed a single directive in the included file, or can you have more? – antun Oct 26 '20 at 03:22
  • 1
    @antun Nginx _(in `/etc/nginx/nginx.conf`)_ already automatically includes in `/etc/nginx/conf.d/*.conf` into it's http section, so you should place your include file somewhere else, nginx uses `/etc/nginx/snippets/` for instance. – andrerom Sep 15 '21 at 12:56