Basics of Nginx for Frontend Developers
Nginx is a high-performance, open-source web server that frontend developers often interact with for serving web applications and static assets.
It’s known for its efficiency, low memory footprint, and ability to handle high concurrency.
For frontend development, Nginx is primarily used in two ways:
- Serving Static Files: Delivering your HTML, CSS, JavaScript, images, and other static assets directly to the user’s browser.
- Reverse Proxy: Routing client requests to different backend services or local development servers.
Basic Syntax
Server block (Virtual Host)
Server block defines how Nginx handles requests for a specific domain or IP.
Think of it like a virtual host — each server block corresponds to one website, app, or API.
If your Nginx config is a book, each server block is a chapter dedicated to one domain.
server {
listen 80;
server_name example.com www.example.com;
location / {
# Configuration for handling requests
}
}
Basic Server directives
listen 80; # Port to listen on
listen 443 ssl; # SSL port
server_name example.com; # Domain name
root /var/www/html; # Document root
index index.html index.php; # Default index files
error_log /var/log/nginx/error.log; # Error log path
access_log /var/log/nginx/access.log; # Access log path
Redirect http to https
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
Location block
location {...}blockroot— directory where Nginx looks for filestry_files $uri /index.html;— ensures client-side routing works (SPA fallback)proxy_pass— forwards/apicalls to your backend (Node, Python, etc.)
Nginx File Locations
# The main entry point for Nginx configuration
/etc/nginx/nginx.conf
# Individual site configurations (virtual hosts)
/etc/nginx/sites-available/
# Contains symlinks to files in sites-available/
/etc/nginx/sites-enabled/
# Logs by default
/var/log/nginx/access.log
/var/log/nginx/error.log
Example: Serve Static App
server {
listen 80;
server_name yourdomain.com;
location / {
root /var/www/my-app/build;
index index.html;
try_files $uri $uri/ /index.html; # Essential for Single Page Applications (SPAs)
}
}
Example: Reverse Proxy
server {
listen 80;
server_name localhost;
location /api/ {
# Forward any request to /api/ to the backend running on port 8080
proxy_pass http://localhost:8080/;
# You may need to add headers for the backend to work correctly
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location / {
# Serve the local development frontend server running on port 3000
proxy_pass http://localhost:3000;
}
}
Basic Commands
- Install nginx
sudo apt-get update
sudo apt-get install nginx
- Check nginx version
nginx -v
- Start/Stop/Restart nginx
sudo service nginx start
sudo service nginx stop
sudo service nginx restart
- Reload config without downtime
sudo systemctl reload nginx
- Test configuration for syntax errors
sudo nginx -t