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. – HopelessN00b Oct 8 '12 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. – Nikolay Fominyh Oct 8 '12 at 8:51
14

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;
  }         
}
2
  • 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 3:22

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.