How to Configure Nginx: Basic Syntax and Example
To configure
nginx, create or edit its main configuration file usually located at /etc/nginx/nginx.conf. Use server blocks inside http context to define how Nginx handles requests, then reload Nginx with sudo nginx -s reload to apply changes.Syntax
The basic Nginx configuration uses a hierarchical structure with contexts like http, server, and location. Each block defines settings for handling web traffic.
- http: Main context for web server settings.
- server: Defines a virtual server with domain and port.
- location: Specifies how to respond to specific URL paths.
- directives: Settings inside blocks, ending with a semicolon.
nginx
http {
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html index.htm;
}
}
}Example
This example configures Nginx to serve a website on port 80 for example.com. It serves files from /var/www/html and uses index.html as the default page.
nginx
events {
worker_connections 1024;
}
http {
server {
listen 80;
server_name example.com www.example.com;
location / {
root /var/www/html;
index index.html index.htm;
}
}
}Output
Nginx starts successfully and serves files from /var/www/html when accessing http://example.com
Common Pitfalls
Common mistakes when configuring Nginx include:
- Forgetting the semicolon
;at the end of directives. - Using incorrect file paths for
rootorindex. - Not specifying
server_name, causing default server to respond. - Failing to reload Nginx after changes with
sudo nginx -s reload.
Always check configuration syntax with sudo nginx -t before reloading.
nginx
## Wrong: Missing semicolon
server {
listen 80
server_name example.com
}
## Right: Semicolons added
server {
listen 80;
server_name example.com;
}Quick Reference
| Directive | Purpose | Example |
|---|---|---|
| listen | Port Nginx listens on | listen 80; |
| server_name | Domain names served | server_name example.com www.example.com; |
| root | Directory for website files | root /var/www/html; |
| index | Default file to serve | index index.html index.htm; |
| location | URL path handling | location /images/ { ... } |
Key Takeaways
Edit /etc/nginx/nginx.conf or files in /etc/nginx/conf.d/ to configure Nginx.
Use server blocks inside http context to define websites and ports.
Always end directives with semicolons and check syntax with sudo nginx -t.
Reload Nginx with sudo nginx -s reload after changes to apply them.
Use root and index directives to specify website files and default pages.