What is the variable scope in a nginx config file?

What is the variable scope in a nginx config file?

  • Is everything declared inside a server block only usable inside that block?

  • Can variables declared in the http block be used inside each server block?

Thanx.

2 Replies

-The stuff inside a server block cannot be accessed within another server block. Each server block counts as it's own vhost. You can place each server block within it's own file if you wish, then within the http block, you can load it via an include line, such as:

include /etc/nginx/vhosts/yoursite.com
include /etc/nginx/sites-enabled/*

The first line specifically tell nginx specifically what vhost file to load. The second tells it to load everything within /etc/nginx/sites-enabled.

-Generally speaking, anything within the http block is included in your server block. So if you have something like:

http {
index index.htm index.html;
server {
listen 80;
server yoursite.com;
root /srv/www/yoursite.com/html;
}
server {
listen 80;
server another.yoursite.com;
root /srv/www/another.yoursite.com/html;
}
}

This will tell nginx that the index line for both of your server blocks will be the same.

Most settings declared in a parent block (e.g. logging, compression, etc.) will be inherited by all child blocks unless specifically overridden.

But sometimes you'll come across slightly unintuitive behavior. For example, I discovered in this thread that none of the FastCGI parameters defined in a parent block will be inherited by a child block if the child block contains any parameters of its own. So if you want to use different FastCGI parameters in different blocks, you need to redefine all of them every single time.

So, push as much as you can to upper-level blocks without breaking things, and make liberal use of includes to prevent repeating yourself in other cases. FastCGI is a case where you pretty much need to use includes, which is why most default configurations already do so.

This official wiki page contains a number of other useful tips on reducing redundancy and improving performance. Some of the configuration directives, however, might not be available on older versions of nginx that come with Ubuntu LTS releases.

Reply

Please enter an answer
Tips:

You can mention users to notify them: @username

You can use Markdown to format your question. For more examples see the Markdown Cheatsheet.

> I’m a blockquote.

I’m a blockquote.

[I'm a link] (https://www.google.com)

I'm a link

**I am bold** I am bold

*I am italicized* I am italicized

Community Code of Conduct