How to Use Nginx as a Web Server: A Practical Setup Guide
Nginx is a high-performance web server celebrated for its speed, stability, and minimal resource usage. Whether you are hosting a simple static site or preparing for a high-traffic application, Nginx is a robust choice. This tutorial walks you through installation, configuration, and virtual host setup.
Before you begin, make sure you have sudo access to a Linux server. Update your package lists and install Nginx from the official repository. On Ubuntu or Debian, run sudo apt update then sudo apt install nginx. The service starts immediately after installation.
Installing and Verifying Nginx
Verify the service runs with systemctl status nginx. Check your server’s IP in a browser for the welcome page, confirming Nginx is working.
Creating a Basic Server Block
Server blocks are like virtual hosts. Instead of editing the main nginx.conf file, create a dedicated configuration file in /etc/nginx/sites-available/. Name it after your domain, e.g., example.com.
Example Configuration
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com;
index index.html;
}
This block tells Nginx to listen on port 80 and serve content from the specified document root. Place your HTML files inside /var/www/example.com.
Enabling Your Site
To activate the site, create a symbolic link to the sites-enabled directory, then test and reload Nginx:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/sudo nginx -tchecks for syntax errors.sudo systemctl reload nginxapplies the changes.
If the test passes, your website is now live. Repeat this process for multiple domains.
Configuring a Reverse Proxy
Nginx is also widely used as a reverse proxy. To forward requests to a local application running on port 3000, add a location block:
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
}
Perfect for Node.js or Python apps running behind Nginx.
Conclusion
Nginx is a versatile web server that scales from simple static hosting to complex proxying. Start with these basics, then explore SSL, caching, and load balancing for production hardening.