Nginx Beginners' Tutorial
Install Nginx
Ubuntu
sudo apt update
sudo apt install nginx
Mac OS
brew install nginx
The Structure Of Configuration File
The nginx configuration files are usually located in the /etc/nginx/ directory.
- Main Site Configuration:
/etc/nginx/nginx.conf - Site Configuration:
/etc/nginx/site-available/(linked to/etc/nginx/site-enabled) - Global Configuration:
user www-data; # User running Nginx
worker_processes auto; # Number of worker processes
error_log /var/log/nginx/error.log; # Error log path
pid /run/nginx.pid; # PID file path
events {
worker_connections 768; # Max connections per worker
}
http {
include /etc/nginx/mime.types; # Supported MIME types
default_type application/octet-stream;
# Access log format
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on; # Efficient file transfer
keepalive_timeout 65; # Long connection timeout
# Include additional site configurations
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
Basic Configuration Examples:
Static Website
server{
listen 80;
server_name example.com; # our domain
location /{
root /vat/www/html; # website directory
index index.html; # default index file
try_files $uri $uri/ =404; # 404 file
}
}
Reverse Proxy
server{
listen 80; # listen port
server_name example.com;
location /{
proxy_pass http://127.0.0.1:3000; # Forward to 3000 port
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Load balancing
upstream backend{
least_conn; # Least connection strategy (alternatives: round-robin, ip_hash)
server 10.0.0.1:80 weight=3; # Weight 3
server 10.0.0.2:80; # Default weight 1
server 10.0.0.3:80 backup; # Backup server
}
server{
listen 80;
server_name example.com;
location /{
proxy_pass http://backend;
}
}
Config HTTPS
server{
listen 443 ssl;
server_name example.com
ssl_certificate /path/to/your/certificater;
ssl_certificate_key /path/to/your/key;
location / {
proxy_pass http://127.0.0.1:3000;
}
}
Common Commands
start stop restart
sudo systemctl start nginx
sudo systemctl stop nginx
sudo systemctl restart nginx