Nginx is a high-performance web server, reverse proxy, load balancer, and HTTP cache.
Installation
# Debian / Ubuntu
sudo apt install nginx
# RHEL / CentOS / Arch Linux
sudo dnf install nginx
sudo pacman -S nginxService Management
sudo systemctl enable --now nginx
sudo systemctl status nginx
sudo systemctl restart nginx
sudo systemctl reload nginx # Gracefully reload configuration without dropping connectionsConfiguration File Locations
- Main Config:
/etc/nginx/nginx.conf - Server Blocks (Virtual Hosts):
- Ubuntu/Debian:
/etc/nginx/sites-available/(symlinked to/etc/nginx/sites-enabled/) - RHEL/CentOS:
/etc/nginx/conf.d/
- Ubuntu/Debian:
- Document Root:
/var/www/html/or/usr/share/nginx/html/
Testing Configuration Syntax
Always test your configuration before reloading Nginx.
sudo nginx -t
# Output should say:
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successfulBasic Server Block (Static Website)
Create a file at /etc/nginx/sites-available/example.com:
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
}Enable it (Ubuntu/Debian) by creating a symlink:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginxNginx as a Reverse Proxy
Nginx is commonly used to proxy requests to backend application servers (like Node.js, Python, or Java).
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_cache_bypass $http_upgrade;
}
}Logs
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log