Nginx config with less code

Estacio
criciumadev
2 min readSep 5, 2016

--

Configure nginx and with less code, less errors.

Introduction

Recently I had to reconfigure many times servers in nginx. Most companies have many configurations only in the server and make life your life more complicated and it gets harder when the same configurations are very complex, in one single file.

That's why I use one structure, how I recently see in the nginx > 1.10.x the structure is the folder "/servers".

This folder is way better than "sites-enabled" or "sites-available" presented in the last versions. And this is possible now, in the current version.

How?

Open the "nginx.conf" and add in the http block this line : “include servers/*” now you have a folder that makes sense.

Another approach is create another folder "includes" in this folder you can put the common server configurations, this gives us a pieces for reusing in many server configurations, working with less code and avoiding errors.

Examples

In "nginx.conf" add

include servers/*;

File "localhost" in the folder "servers"

#servers/localhost
server {
listen 80;
server_name localhost;
set $front "/www/master";
set $api "http://localhost:300";
include includes/front.locations;
include includes/api.locations;
}

File “front.locations” in the folder “includes”

index index.html;location /assets {
autoindex on;
alias $front;
try_files $uri $uri/ /index.html =404;
}

File “api.locations” in the folder “includes”

location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_intercept_errors on;
proxy_pass $api;
}

Conclusion

Try to break all configuration files in small parts, this is the best way for understandability and less complexibility. And the developers will not be scared when they need to reconfigure the servers.

Thanks for reading and if you have a different or complement opinion write me.

--

--