Nginx Cheatsheet
Configuration files
-
/etc/nginx/nginx.conf
-
/etc/nginx/sites-available/*
-
/etc/nginx/sites-enabled/*
Master and worker processes
- master process reads and evaluate configurations, and maintain worker processes.
- worker processes process the actual requests
- number of worker processes can be configured
-
Functions of Nginx?
- weberver, load balancer, reverse proxy
Key features of Nginx?
# start stop restart status
$ sudo service nginx start
$ sudo service nginx stop
$ sudo service nginx restart
$ systemctl status nginx
# check nginx configuration for syntax errors
$ sudo nginx -t
$ nginx -s stop
$ nginx -s reload
$ nginx -s reopen
$ nginx -s quit
Basic server block structure
server {
listen 80;
server_name example.com www.example.com;
location / {
# other configurations
}
}
Redirect HTTP to HTTPS
server {
listen 80;
server_name example.com
return 301 https://$host$request_uri;
}
Root Directive
server {
...
location / {
root /path/to/your/files;
index index.html;
}
...
}
Proxy Pass
server {
...
location /app {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
...
}
URL Rewriting
server {
...
location /blog {
# removes "/blog" in url
rewrite ^/blog/(.*)$ /$1 break;
}
...
}
SSL Configuration
server {
listen 443 ssl;
server_name example.com;
...
ssl_certificate /path/to/your/certificate.crt;
ssl_certificate_key /path/to/your-private.key;
...
}
Load Balancing
upstream backend {
# load balancing method:
# default is round robin; least_conn; ip_hash;
server backend1.example.com weight=5;
server backend2.example.com;
server 192.0.0.1 backup;
}
server {
...
location / {
proxy_pass http://backend;
}
}
Serving images with regular expression
server {
...
location ~ \.(gif|jpg|png)$ {
root /data/images;
}
}
FastCGI
server {
location / {
fastcgi_pass localhost:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param QUERY_STRING $query_string;
}
location ~ \.(gif|jpg|png)$ {
root /data/images;
}
}
Limiting request size
http {
# in http
...
# default is 1M;
client_max_body_size 100M;
}
server {
# or in server
...
client_max_body_size 100M;
}
location /uploads {
# or in location
...
client_max_body_size 100M;
}