nginx configuration examples

default http service

server {
    listen 80 default_server;
    listen [::]:80 default_server;

    root /var/www/html;

    index index.html index.htm index.nginx-debian.html;

    server_name _;

    location / {
        try_files $uri $uri/ =404;
    }
}

https service

server {
    listen 443;
    server_name cfig.me;

    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;

    ssl on;
    ssl_certificate 2017/213964558630897.pem;
    ssl_certificate_key 2017/213964558630897.key;
    ssl_session_timeout 5m;
    ssl_protocols SSLv3 TLSv1;
    ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;
    ssl_prefer_server_ciphers on;

    location / {
        try_files $uri $uri/ =404;
    }
}

reverse-proxy for localhost:8080

nginx handles https and redirects all requests to local service listening on 8080.

upstream api_node_js {
    server    127.0.0.1:8080;
}
server {
    listen 443;
    server_name api.cfig.me;

    root /var/www/html;
    index index.html index.htm index.nginx-debian.html;

    ssl on;
    ssl_certificate 2017_api_cfig_me/213972664770897.pem;
    ssl_certificate_key 2017_api_cfig_me/213972664770897.key;

    ssl_session_timeout 5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers AESGCM:ALL:!DH:!EXPORT:!RC4:+HIGH:!MEDIUM:!LOW:!aNULL:!eNULL;
    ssl_prefer_server_ciphers on;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;
        proxy_pass http://api_node_js;
        proxy_redirect off;
    }
}

‘proxy_set_header’ will change http headers passed to local 8080, ‘X-Real-IP’ and ‘X-Forwarded-For’ now has the real src IP as shown below:

file service

server {
    listen 4573 default_server;
    listen [::]:4573 default_server;
    server_name _;

    root /var/download;
    autoindex on;
    autoindex_exact_size on;
    autoindex_localtime on;

    index index.html index.htm index.nginx-debian.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

https gerrit with basic http auth

server {
    listen 80;
    server_name g.cf1g.com;
    return    301 https://$server_name$request_uri;
}

server {
    listen 443;
    server_name g.cf1g.com;

    location / {
        auth_basic              "Gerrit 2.12";
        auth_basic_user_file    /etc/nginx/htpwd.conf;
        proxy_pass              http://localhost:8081;
        proxy_set_header        X-Forwarded-For $remote_addr;
        proxy_set_header        Host $host;
    }

    ssl on;
    ssl_certificate 2016/1_cf1g.com_bundle.crt;
    ssl_certificate_key 2016/cf1g.rsa;

    ssl_session_timeout 5m;

    ssl_protocols SSLv3 TLSv1;
    ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;
    ssl_prefer_server_ciphers on;
}