Digital Studium

Blog about Linux, DevOps and cloud technologies

๐ŸŒ ะ ัƒััะบะธะน

Digital Studium

Nginx: Sample Configuration Files


๐Ÿง˜ By: Konstantin Shutkin

Sometimes there is a need to quickly create an nginx configuration file: for hosting a static website, for proxying requests to upstream server, etc.

This article provides simple examples of Nginx configs for different purposes.

For the following configs to work, you need to put them in the path /etc/nginx/conf.d/<some_name>.conf, then check config validity:

nginx -t

Then run the command to apply the config:

sudo service nginx reload

Example 1: hosting a static site.

server {
  listen 80;
  server_name example.com www.example.com;

  access_log /var/log/nginx/example.com.log;

  location / {
    root /var/www/example.com;
    index index.html;
  }
}

Example 2: proxy server

server {
  listen 80;
  server_name example.com www.example.com;

  access_log /var/log/nginx/example.com.log;

  location / {
    proxy_pass http://127.0.0.1:5000;
    proxy_buffering off;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Port $server_port;
  }
}

Example 3: caching proxy

In /etc/nginx/nginx.conf add:

http {
  proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=STATIC:10m;
  inactive=24h max_size=1g;
}

In /etc/nginx/conf.d put the following config:

server {
  listen 80;
  server_name example.com www.example.com;

  access_log /var/log/nginx/example.com.log;
  location / {
    proxy_pass http://1.2.3.4;
    proxy_set_header Host $host;
    proxy_cache STATIC;
    proxy_cache_valid 200 1d;
    proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
  }
}