Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@lifeeric
Last active October 1, 2020 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lifeeric/f3e10d4ba9b40aed892559a6892b99a7 to your computer and use it in GitHub Desktop.
Save lifeeric/f3e10d4ba9b40aed892559a6892b99a7 to your computer and use it in GitHub Desktop.

Nginx Cheat sheet

install from source code

building nginx server the source is the ablity to add custom module,or essentially extend the standard nginx functionality.

required libraries:

$ sudo apt install libpcre3 libpcre3-dev zlib1g zlib1g-dev libssl-dev

buid it:

# ./configure --sbin-path=/usr/bin/nginx --conf-path=/etc/nginx/nginx.conf \
 --error-log-path=/var/log/nginx/err.log --http-log-path=/var/log/nginx/access.log \
  --with-pcre --pid-path=/var/run/nginx.pid --with-http_ssl_module

compile code

# make

install

# make install

adding systemd https://www.nginx.com/resources/wiki/start/topics/examples/systemd/

# systemctl daemon-reload

and now start the nginx

# systemctl start nginx

startup on boot:

systemctl enable nginx

Location

prefix match

        location /greet {
            return 200 'Hello from NGINX';
        }

Exact Match

        location = /greet {
            return 200 "Hello from NGINX exact match";
        }

Regex Match, tilde sign

 location ~ /greet[0-9]  {
            return 200 "Hello from NGINX location - REGEX Match";
        }

insensitive case matching

location ~* /greet[0-9] {
            return 200 "Hello from NGINX - REGEX Match";
        }

Preferential prefix match

        location ^~ /Greet2 {
            return 200 'Hello from NGINX';
        }

if condition

# check static API key
       if ( $arg_apikey != 1234 ) {
           return 401 "Incorrect API key";
       }

variables

        location /inspect {
             return 200 "$host\n$uri\n$args";
        }


        location /inspect {
            return 200 "Name: $arg_name";
        }

logic

    set $weekend 'No';

     # check if weekend
     if ( $date_local ~ 'Wednesday|Thursday' ) {
         set $weekend 'Yes';
     }

         location /is_weekend {
         return 200 $weekend;
     }

Redirect

    Temperary redirct
location /logo {
    return 307 /images/demo/960x360.gif;
}

Rewrite

        # need more system resources than return
        rewrite ^/user/\w+ /greet;

        location /greet {
            return 200 "Hello rewrite user";
        }

capita group

        # need more system resources than return
        rewrite ^/user/(\w+) /greet/$1;

        location = /greet/john {
            return 200 "Hello john";
        }

last match, no need to evaluate more uri

        rewrite ^/user/(\w+) /greet/$1 last;
        rewrite ^/greet/john /logo;

if the first file exists, so serve it otherwise serve the next one

        try_files /images/demo/960x360.gif /john;
        
        # using with variable
        try_files $uri /images/demo/960x360.gif /john;

404

        try_files $uri /logo.png /greet /404;

        location /404 {
            return 404 "The file couldn't be found!";
        }

keeping name

        try_files $uri /logo.png /greet @404;

        location @404 {
            return 404 "The file couldn't be found!";
        }

Error Handling

custom loggin files

   location /secure {
            access_log /var/log/nginx/secure.access.log;
            access_log /var/log/nginx/access.log;
            return 200 "Welcome to secure area."
        }

blocking log for certain requrest

        location /secure {
            access_log off;
            return 200 "Welcome to secure area.";
        }

Configure PHP

installing PHP-FPM to configure with nginx

$ sudo apt install php-fpm

load the index file once the request has been made to our domain

    server {
        listen 80;
        server_name 100.26.249.49;

        root /site/demo;

        index index.php index.html;

    }

full demo with fastCGI, and permission denied(solved)

user www-data;

events{}


http {

    include mime.types;
    index index.html;

    server {
        listen 80;
        server_name 100.26.249.49;

        root /site/demo/basic-89;

        index index.php index.html;

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

        location ~\.php$ {
            #Pass php request to php-fpm service (fastcgi)
            include fastcgi.conf;
            fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        }
    }
}

increasing the number of worker processes

user www-data;

worker_processes 2;

events{}

# check now
systemctl status nginx

checking cpu on server there's two command, nproc and lscpu in *nix system.

(auto) for numbers of cpus you want to have worker, keep it auto instead

worker_processes auto;

checking limit of concurrent request ulimit -n.

keeping max concurrent request in nginx

event {
 worker_connections <ulimit -n number here> 1024;
}

changin pid without rebuilding nginx server again

pid /var/run/new_nginx.pid;
event{}

Header

add header, the css,js,png and jpg will be cached for 1month in the user machine

location ~* \.(css|js|jpg|png)$ {
                access_log off;
                add_header Cache-Control public;
                add_header Pragma public;
                add_header Vary Accept-Encoding;
                expires 1M;
        }

Gzip

compressing request using gzip

http {
  gzip on;
  gzip_comp_level 3;
  
  gzip_types text/css;
  gzip_types text/javascript;
}

HTTP 2.0

adding http 2, also need ssl certificate

# openssl req -x509 -days 10 -nodes -newkey rsa:2048 -keyout /etc/nginx/ssl/self.key -out /etc/nginx/ssl/self.crt

rebuild the nginx server with flag --with-http_v2_module

nginx.conf

server {
 listen 443 ssl http2;
 
 ssl_certificate /etc/nginx/ssl/self.crt;
 ssl_certificate_key /etc/nginx/ssl.key;
}

TSL

generate dhparam openssl dhparam -out /etc/nginx/ssl/dhparam.pem 2048

server {
 listen 443 ssl http2;
 
 ssl_certificate /etc/nginx/ssl/self.crt;
 ssl_certificate_key /etc/nginx/ssl.key;
 
  # Disable SSL
 ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

 # Optimise cipher suits
 ssl_prefer_server_ciphers on;
 ssl_ciphers ECDH+AESGCM:ECDH+AES256:ECDH+AES128:DH+3DES:!ADH:!AECDH:!MD5;

 # Enable DH Params
 ssl_dhparam /etc/nginx/ssl/dhparam.pem;
 
  # Enabl HSTS for a year
 add_header Strict-Transport-Security "max-age=31536000" always;

 # SSL sessions
 ssl_session_cache shared:SSL:40m;
 ssl_session_timeout 4h;
 ssl_session_tickets on;

}

http to https redirection

when accessing http://example.com you might get error, to avoid the error redirect to https://example.com

http {
 
 # redirect all traffic to HTTPS
 server {
   listen 80;
   server_name 127.0.0.1/www.example.com;
   
   return 301 https://$host$request_uri;
 }
 
 server {
   # all your configuration code  goes here..
 }
}

Rate Limiting

first you need to install siege in your distro: sudo apt install siege. checking siege working siege -v -r 2 -c 5 url

include mime.types;

# right down the min.types;
# Define Limit zone
# 60 request / 1min
# to MyZONE
limit_req_zone $request_uri zone=MYZONE:10m rate=60r/m;

server {
 # all code here
 
 location / {
        limit_req zone=MYZONE;
        try_files $uri $uri/ =404;
    }
}

adding burst to specific location. burst mean keeping the request in promsie (for grasping like js).

 location / {
    limit_req zone=MYZONE burst=5;
    try_files $uri $uri/ =404;
}

nodelay Learn more about nodelay

limit_req zone=MYZONE burst=5 nodelay;

Admin Area ( Basic Auth )

first you need to install apt install apache2-utils second generate .htpasswd file htpasswd -c /etc/nginx/.htpasswd user1

location / {
  auth_basic "Secure Area";
  auth_basic_user_file /etc/nginx/.htpasswd; 
  # .. codes...
}

Server Push

receiving multiple request at same moment ( by one request in http 2.0)

location = /index.html {
   # all the files need to be available for client side
   http2_push /style.css
   htt2_push /logo.png
}

Example

 root /site/demo/basic-89;

        try_files $uri /logo.png /greet @404;

        location @404 {
            return 404 "The file couldn't be found!";
        }

        # need more system resources than return
        rewrite ^/user/(\w+) /greet/$1 last;
        rewrite ^/greet/john /logo;

        location /greet {
            return 200 "Hello rewrite user";
        }

        location = /greet/john {
            return 200 "Hello john";
        }

        # Temperary redirct
        location /logo {
            return 307 /images/demo/960x360.gif;
        }


        # create var
        set $weekend 'No';

        # check if weekend
        if ( $date_local ~ 'Wednesday|Thursday' ) {
            set $weekend 'Yes';
        }
           # check static API key
           if ( $arg_apikey != 1234 ) {
               return 401 "Incorrect API key";
           }
        location /inspect {
            return 200 "$host\n$uri\n$args";
        }
        location /is_weekend {
            return 200 $weekend;
        }
        # prefix match
        location /Greet2 {
            return 200 'Hello from NGINX';
        }
        # Exact
        location = /greet {
            return 200 "Hello from NGINX exact match";
        }
        location ~ /greet[0-9]  {
            return 200 "Hello from NGINX location - REGEX Match";
        }
        location ~* /greet[0-9] {
            return 200 "Hello from NGINX - REGEX Match";
        }
        # Preferential prefix match
        location ^~ /Greet2 {
            return 200 'Hello from NGINX';
        }
        ```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment