Nginx is a fast, lightweight web server and reverse proxy. It can serve a static site on its own, or sit in front of PHP, Node.js, Python or Docker apps.
1. Install Nginx
Ubuntu and Debian start it automatically:
sudo apt update
sudo apt install -y nginxAlmaLinux and Rocky Linux:
sudo dnf install -y nginx
sudo systemctl enable --now nginx2. Open the firewall
sudo ufw allow 'Nginx Full' # UFW
sudo firewall-cmd --permanent --add-service={http,https} && sudo firewall-cmd --reload # firewalldNow visit http://203.0.113.25 in your browser. You should see the Nginx welcome page.
3. Create a folder for your site
sudo mkdir -p /var/www/example.com/html
echo '<h1>It works</h1>' | sudo tee /var/www/example.com/html/index.html4. Add a server block
On Ubuntu and Debian, create /etc/nginx/sites-available/example.com. On AlmaLinux and Rocky, create /etc/nginx/conf.d/example.com.conf. The content is the same:
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}On Ubuntu and Debian, enable it with a symlink:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/5. Test, then reload
Always test before reloading. A reload with a broken file is refused, but a restart would take the site down:
sudo nginx -t
sudo systemctl reload nginxTip: Make sudo nginx -t && sudo systemctl reload nginx a habit. The reload only runs if the test passes.
6. Point your domain
Create an A record for example.com (and www) at your DNS provider with your server's IP. Once it resolves, the site loads by name. Then add HTTPS: Secure Nginx with a free Let's Encrypt certificate.
Where things live
- Logs:
/var/log/nginx/access.logand/var/log/nginx/error.log. - Main config:
/etc/nginx/nginx.conf. - Follow errors live:
sudo tail -f /var/log/nginx/error.log.
Troubleshooting
- Welcome page instead of your site: the
server_namedoes not match the name in the browser, or (Ubuntu/Debian) the symlink insites-enabledis missing. - 403 Forbidden: Nginx cannot read the files or there is no
index.html. Check permissions withnamei -l /var/www/example.com/html/index.html. On AlmaLinux/Rocky, files moved in from elsewhere may have the wrong SELinux label:sudo restorecon -Rv /var/www. - Page does not load at all: check the firewall (step 2) and that Nginx runs:
systemctl status nginx.
