Skip to main content

Nginx Virtual Host Configurations and Syntax

This document contains examples and syntax for setting up Nginx virtual hosts.

Basic Structure of a Virtual Host

server {
listen 80;
server_name example.com www.example.com;

root /var/www/example.com/html;
index index.html index.htm index.php;

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

error_page 404 /404.html;
location = /404.html {
root /var/www/example.com/html;
}
}

SSL Configuration

server {
listen 443 ssl;
server_name example.com www.example.com;

ssl_certificate /etc/nginx/ssl/example.com.crt;
ssl_certificate_key /etc/nginx/ssl/example.com.key;

root /var/www/example.com/html;
index index.html index.htm;

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

Reverse Proxy

server {
listen 80;
server_name api.example.com;

location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}

Load Balancer

upstream backend {
server backend1.example.com;
server backend2.example.com;
}

server {
listen 80;
server_name example.com;

location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}

Redirect HTTP to HTTPS

server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}

Custom 404 Error Page

server {
listen 80;
server_name example.com;

root /var/www/example.com/html;

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

error_page 404 /custom_404.html;
location = /custom_404.html {
root /var/www/example.com/html;
}
}

Gzip Compression

server {
listen 80;
server_name example.com;

root /var/www/example.com/html;

gzip on;
gzip_types text/plain application/xml text/css text/javascript application/json application/javascript;
}

PHP with FastCGI

server {
listen 80;
server_name example.com;

root /var/www/example.com/html;
index index.php index.html index.htm;

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

location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}

Caching Static Files

server {
listen 80;
server_name example.com;

root /var/www/example.com/html;

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

location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg|eot)$ {
expires 6M;
access_log off;
}
}

This document covers common use cases. Adjust paths and settings according to your specific requirements.