Nginx password protect one domain and avoid config duplication

configurationnginx

I got 2 domains dev.domain.com and beta.domain.com. At the moment I have one server section (default) with a bunch of specific locations and rules. Now I need to password protect beta.domain.com. Is there a way to do this without creating additional server section and essentially duplicating all my location and other rules?

Generally I would like to know how other people manage complex nginx configurations. Do they just copy sections (duplicate) or include common rules somehow?

Best Answer

The simplest way to share a configuration between multiple server blocks, is using the include directive. For instance:

/etc/nginx/conf.d/mysite.inc:

#...locations and rules...

/etc/nginx/sites-available/dev.domain.com:

server {
    server_name dev.domain.com;
    root /path/to/root;
    include /etc/nginx/conf.d/mysite.inc;
}

/etc/nginx/sites-available/beta.domain.com:

server {
    server_name beta.domain.com;
    root /path/to/root;
    include /etc/nginx/conf.d/mysite.inc;
    location / {
        auth_basic "Authentication Required";
        auth_basic_user_file  /path/to/authfile;
    }
}