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.

2
  • Please take a moment to read our FAQ. Your question appears off-topic for this site to me. Oct 8, 2012 at 2: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. Oct 8, 2012 at 8:51

1 Answer 1

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;
  }         
}
3
  • 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. Nov 20, 2014 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, 2020 at 3: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, 2021 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.