Nginx

Table of Contents

Beginner's Guide

$ nginx -s stop   # fast shutdown
$ nginx -s quit   # graceful shutdown
$ nginx -s reload # reloading the configuration file
$ nginx -s reopen # reopening the log files

Processes

Directives

Reference

core

events

#+BEGIN_EXAMPLE
  events {
      use kqueue;
      worker_connections 2048;
  }

include

include mime.types;
include vhosts/*.conf;

workerprocesses

worker_processes auto;

http

location

location = / {
    [ configuration A ]
}

location / {
    [ configuration B ]
}

location /documents/ {
    [ configuration C ]
}

# '^~' modifier skips regex check
location ^~ /images/ {
    [ configuration D ]
}

# '~*' modifier for regex case insensitive match
# '~' for case sensitive
location ~* \.(gif|jpg|jpeg)$ {
    [ configuration E ]
}
/                        -> A
/index.html              -> B
/documents/document.html -> C
/images/1.gif            -> D
/documents/1.jpg         -> E

types

types {
    text/html  html;
    image/gif  gif;
    image/jpeg jpg;
}

proxy

proxypass

If the proxy_pass directive is specified with a URI, then when a request is passed to the server, the part of a normalized request URI matching the location is replaced by a URI specified in the directive:

location /name/ {
    proxy_pass http://127.0.0.1/remote/;
}

/name will be replaced with /remote

If proxy_pass is specified without a URI, the request URI is passed to the server in the same form as sent by a client when the original request is processed, or the full normalized request URI is passed when processing the changed URI:

location /name/ {
    rewrite    /name/([^/]+) /users?name=$1 break;
    proxy_pass http://127.0.0.1;
}

In this case, the URI specified in the directive is ignored and the full changed request URI is passed to the server.

proxyredirect

# will rewrite this string to “Location: http://frontend/one/some/uri/”.
proxy_redirect http://localhost:8000/two/ http://frontend/one/;

proxyhideheader

rewrite

rewrite

location  /foo {
  rewrite /foo(.*) /$1  break;
  proxy_pass         http://localhost:3200;
  proxy_redirect     off;
  proxy_set_header   Host $host;
}

Details

site-enabled, site-available

##
# Virtual Host Configs
##

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

Use Cases

Reverse Proxy with preserving request host

It seems that some hosts use Host header to redirect the client. nginx passes $proxy_host, which contains the address of proxied server, by default.

Some proxied servers redirect the client to a URL of their original host. By setting proxy_set_header Host $host, nginx passes Host as its own address. By this, nginx keep clients communicating with it.

user www-data www-data;
worker_processes auto;

events {
}

http {
  server {
    listen 80;
    location / {
      proxy_pass http://localhost:8080;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
    }
  }
}

Server Block Examples

Links