Installation
Bash
sudo apt update && sudo apt install -y nginx
sudo systemctl enable --now nginx
sudo nginx -t # check configuration syntax
sudo nginx -s reloadConfiguration File Structure
CODE
/etc/nginx/
├── nginx.conf
├── sites-available/
│ └── myapp.conf
└── sites-enabled/
└── myapp.conf -> ../sites-available/myapp.confServing Static Files
Nginx
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
gzip on;
gzip_types text/plain text/css application/json application/javascript;
}Reverse Proxy
Nginx
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
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_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 30s;
proxy_read_timeout 60s;
}
}Load Balancing
Nginx
upstream backend {
least_conn;
server 10.0.0.1:3000 weight=3;
server 10.0.0.2:3000;
server 10.0.0.3:3000 backup;
}
server {
listen 80;
location / {
proxy_pass http://backend;
}
}Security Headers
Nginx
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
add_header Strict-Transport-Security "max-age=31536000" always;
server_tokens off;Enabling the Configuration
Bash
sudo ln -s /etc/nginx/sites-available/myapp.conf \
/etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginxEditorial note
AI tools may assist drafting. Check the evidence in each guide for whether commands were run and which environment was used. Confirm the current docs for your version before applying instructions, and email us about errors. email us
Topic-related official docs (auto-linked · not per-claim sources)NGINX documentation ↗
Questions & answers
Ask a question about this guide. We'll review and reply.