Nginx

sudo systemctl status nginx
to check the status of nginx


/etc/nginx
configuration files


all configurations to be deployed in conf.d which is an empty folder.
Usually people make it in sites enabled and sites available.

nginx.png
Main:
Number of worker processes
username
process id (pid)
log location

Events

Stream:

HTTP:
Server block

Upstream:

To create a server conf file, go to /etc/nginx/conf.d

server{
listen 80 default_server;
root /var/www/cafe;

server_name _;

index index.htm index.html;

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

To create domain name configuration add A record in domain name provider

server{
listen 80 default_server;
root /var/www/cafe;

server_name jobs.surajg.tech;

index index.htm index.html;

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

You can have multiple domains too like this

server_name jobs.surajg.tech hello.surajg.tech www.surajg.tech;

To create multiple domain hosting

server{
listen 80;
root /var/www/portfolio;

server_name portfolio.surajg.tech;

index index.htm index.html;

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

Basic authentication using nginx

sudo sh -c "echo -n 'codersgyan:' >> /etc/nginx/.htpasswwd"

sudo sh -c "openssl passwd -apr1 >> /etc/nginx/.htpasswd"
server{
listen 80;
root /var/www/dev;

server_name dev.surajg.tech;
auth_basic "Under development site"
auth_basic_user_file /etc/nginx/.htpasswd;

index index.htm index.html;

location /{
try_files $uri $uri/ = 404;
}
}
To create authentication only in admin panel, use the following method
server{
listen 80;
root /var/www/dev;

server_name dev.surajg.tech;
auth_basic "Under development site"
auth_basic_user_file /etc/nginx/.htpasswd;

index index.htm index.html;

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

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

sudo nginx -T : to print the whole configuration content

Reverse Proxy

Pasted image 20231205074030.png

upstream backend{
server localhost:8000;
}

server{
listen 80;
server_name api.surajg.tech;
location /{
proxy_pass http://backend;
}
}

Load Balancing

add_header Cache-Control no-store;
upstream backend{
server localhost:8000;
server localhost:8001;
}

server{
listen 80;
server_name api.surajg.tech;
location /{
add_header Cache-Control no-store;
proxy_pass http://backend;
}
}
server localhost:8000 weight=3;
upstream backend{
server localhost:8000 weight=3;
server localhost:8001 weight=2;
}

server{
listen 80;
server_name api.surajg.tech;
location /{
add_header Cache-Control no-store;
proxy_pass http://backend;
}
}
server localhost:8001 backup;
upstream backend{
server localhost:8000;
server localhost:8001 backup;
}

server{
listen 80;
server_name api.surajg.tech;
location /{
add_header Cache-Control no-store;
proxy_pass http://backend;
}
}
server localhost:8000 down;