- Published on
NGINX server
In NGINX, the server directive defines a virtual server (virtual host). It tells NGINX how to handle requests for a specific domain, IP, or port.
It must be placed inside the http block.
Basic Structure
http {
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
}
Key server Directive Parameters
1️⃣ listen
Defines the IP address and port the server listens on.
listen 80;
listen 443 ssl;
listen 127.0.0.1:8080;
listen [::]:80; # IPv6
Options:
sslhttp2default_server
Example:
listen 80 default_server;
2️⃣ server_name
Specifies the domain names this server responds to.
server_name example.com www.example.com;
Supports:
- Exact names
- Wildcards (
*.example.com) - Regex
server_name *.example.com;
server_name ~^api\d+\.example\.com$;
3️⃣ root
Sets the document root.
root /var/www/app;
4️⃣ index
Defines default file when directory is requested.
index index.html index.htm index.php;
5️⃣ location
Handles specific request paths inside a server block.
location /api/ {
proxy_pass http://backend;
}
6️⃣ SSL Example Server Block
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/nginx/ssl/cert.pem;
ssl_certificate_key /etc/nginx/ssl/key.pem;
location / {
proxy_pass http://localhost:3000;
}
}
Multiple Server Blocks (Virtual Hosts)
server {
listen 80;
server_name site1.com;
root /var/www/site1;
}
server {
listen 80;
server_name site2.com;
root /var/www/site2;
}
NGINX selects the server block based on:
listenmatchserver_namematchdefault_serverif no match
Where It Lives
Usually in:
/etc/nginx/nginx.conf
or
/etc/nginx/conf.d/*.conf
/etc/nginx/sites-available/*