Essential NGINX Configuration - Quick Reference

23-Aug-2023

Generic badge

Create file /etc/nginx/sites-available/example.config and make symlink using the command

sudo ln -s /etc/nginx/sites-available/example.config /etc/nginx/sites-enabled/

After every changes made in example.config. The file should be tested for error free and nginx server should be reloaded to take effect.

sudo nginx -t # To Test
sudo systemctl reload nginx # To Reload
Serving Static Website

Configure NGINX to serve static Website.

server {
        server_name example.com;
        root /var/www/example;
        index index.html index.htm;
        location / {
                try_files $uri /index.html;
        }
        location ~/\.ht {
                deny all;
        }
}
For reverse proxy

Configure NGINX to serve API using reverse proxy.

server {
	server_name api.example.com;
	location / {
	        proxy_pass http://localhost:8085/api/v1/;
	        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-Forwarded-For $proxy_add_x_forwarded_for;
	        proxy_cache_bypass $http_upgrade;
	}
}
For PHP Sites

Configure NGINX to serve PHP Websites.

server {
        server_name example.com;
        root /var/www/example;
        index index.html index.php;
        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }
        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }
        location / {
                try_files $uri $uri/ /index.php?$args;
        }
        location ~* \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        }
        location ~ /\.ht {
                deny all;
        }
}
www to non-www Redirect
server {
  server_name example.com;
  location / {
    ...
  }
}

server {
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}
non-www to www Redirect
server {
  server_name www.example.com;
  location / {
    ...
  }
}

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