Nginx Cheatsheet

Nginx vs Apache

  • Nginx interprets incoming requests as URI locations whereas Apache prefers to interpret requests as filesystem locations
  • Nginx can handle more concurrent processes
  • Nginx requires less resources

Nginx.conf

Overall

  • worker_process
    • sets the number of CPU cores to produce the best performance
    • “auto” sets to the number of CPU cores available
    • use nproc or lscpu to find out the number of CPU cores available and use no more than that

Events { }

  • worker_connections
    • use ulimit -n to find out the number
    • worker_process * worker_connections = total amount of connections accetable
  • multi_accept
    • allows multiple connections at once
    • multi_accept on;

Http { }

  • types
    • map of types to corresponding mime types
    • can be replaced with default list mime.types
      • include mime.types
  • basic settings
    • charset utf-8;
    • sendfile on;
    • tcp_nopush on;
    • tcp_nodelay off;
    • types_hash_max_size 2048;
  • file cache
    • open_file_cache max=1000 inactive=20s;
    • open_file_cache_valid 30s;
    • open_file_cache_min_uses 2;
    • open_file_cache_errors on;
  • fast cgi cache
    • good for caching static responses from the backend
    • fastcgi_cache_path /tmp/nginx_cache levels=1:2 keys_zone=microcache:10m max_size=500m;
      • max_size = disk space or mem space depending on the location of the cache
    • fastcgi_cache_key “schemerequest_methodhostrequest_uri”
      • leaving out each $value represents caching at a level within what’s left out
      • $scheme = http/https
        • leaving out would cache the same for http/https
      • $request_method = GET/POST/etc…
        • leaving out would cache the same for all methods
    • location{fastcgi_cache microcache}
      • can be called in multiple locations within the location directory
    • location {fastcgi_cache_valid 200 60m; }
    • location{fastcgi_pass 127.0.0.1:9000;}
    • add_header microcache-status $upstream_cache_status;
      • to add header for using fastcgi
  • buffer sizes
    • client_body_buffer_size 16k;
    • client_header_buffer_size 1k;
    • client_max_body_size 8m;
    • large_client_header_buffers 2 1k;
  • timeouts
    • client_body_timeout 12;
    • client_header_timeout 12;
    • keepalive_timeout 300;
      • need for repeated handshakes
    • send_timeout 10;
  • server token
    • server_tokens off;
      • hide nginx version info

Server { }

  • listen
    • port that the server listens on
  • server_name
    • domain name
    • ip
  • root
    • static folder of what the server renders on
  • compressing
    • gzip on;
    • gzip_min_length 100;
      • minimum file length to compress
    • gzip_comp_level 3;
      • keep it between 2-4, since it takes more CPU the higher the number
    • gzip_types text/plain;
      • types of files that needs to be compressed
    • gzip_disable “msie6”;
      • disable gzip for certain browsers, some browsers aren’t compatible with compressing
  • adding headers
  • add_header “Cache-Control” “no-transform”;
    • an array types that allows you to add multiple headers to the response

Location { }

  • uri mapping to serve pages
  • many formats and syntax on which uri/uris are served, look up for details while implementing
    • =
      • Exact match
    • ^~
      • Preferential prefix
    • ~&~*
      • Regex match
    • no modifier
      • Prefix match
  • error_log [directory]
    • specify where to log
  • turning the logs off
    • access_log off
    • error_log off
  • try_files
    • try_files $uri = 404;
    • try_files $url [preferred html] = 404;
  • rewrite
    • rewrite ^ /index.html;
    • cache expirations
      • expires 1M;
        • time for cache to expire and have to request again
      • add_header Pragma public;
      • add_header Cache-Control public;
      • add_header Vary Accept-Encoding;
  • logs
    • /var/log/nginx (default)
      • access.log
      • error.log
        • 404 is not logged as error, check access.log

Security

  • listen on 443
    • listen 443 ssl;
  • apply ssl certs
    • ssl_certificate [path_to_.crt];
    • ssl_certificate_key [path_to_.key];
  • autoindex
    • autoindex off;
      • disable auto indexing directories on the server
  • server tokens
    • server_tokens off;
      • hide version of nginx from the headers
  • buffer
    • set the buffer size as described above to prevent buffer overflow attacks
  • user agents
    • if($http_user_agent ~* [bad_agent_name]) {return 403;}
    • if($http_referer ~* [bad_referer_name]) {return 403;}
      • both blocks the corresponding bad agents by return 403 when seen
  • X-Frame-Option
    • add_header X-Frame-Options SAMEORIGN;
      • only allows browser to render a page within a fram or iframe from the same origin

Reverse Proxy

  • proxy_pass
  • header
    • add_header proxied nginx;
      • add the proxied header to the client
    • proxy_set_header proxied nginx;
      • add the proxied header to all requests

Load Balancer

  • upstream
    • 
        upstream servers {
          server localhost:10001;
          server localhost:10002;
          server localhost:10003;
        }
        
        server {
          listen 8888;
          
          location / {
            proxy_pass 'http://servers';
          }
        }
      
  • options
    • ip_hash
      • ties to the main server, if it goes down then uses next server
    • least_conn
      • connects to the lease connected server
    • usage
      • upstream servers{ip_hash;}
      • upstream servers{least_conn;}

2 Replies to “Nginx configuration cheatsheet”

  1. I like the UI you chose for your site, very techy.

    Any reason why you decided to add the ‘{}’ after some of the headers, and not for others? Like ‘Events {}’ vs ‘Reverse Proxy’?

    Also, what is your use case for nginx? It sounds like a cool technology but I have no idea what it does.

    1. Hi anon-not-so-more,

      The reason why I added the ‘{}’ after the headers is to specify that the bullets within are for that specific context (everything followed by ‘{}’ is called context and the configurations within are called directories). Please take a look at this example provided by Nginx : https://www.nginx.com/resources/wiki/start/topics/examples/full/.
      On the other hand, headers such as ‘Reverse Proxy’ represent the specific features in Nginx.

      Nginx is is essentially another layer of web server on top of your applications. It’s able to add serving, caching, media streaming, and reverse proxy for emails and your applications. In addition, it provides features such as header configuration, package compressing, and load balancing.

      These are the basic explanation of what Nginx does, if you’d like to discuss more about it, please feel free to email me at rjzheng@yesterdayilearned.com

      Thank you for your helpful comments,
      Richard

Leave a Reply

Your email address will not be published. Required fields are marked *