This guide installs NGINX from the Ubuntu repositories, opens only the ports you need, and adds a small set of security headers. It assumes a fresh Ubuntu 24.04 server and a user with sudo access.
What is the safest way to install NGINX on Ubuntu? #
Install the nginx package with apt, allow only HTTP and HTTPS through UFW, and validate every change with nginx -t before reloading. This keeps the default packages patched by Ubuntu security updates and avoids exposing unused services, which is the safest baseline for a new server.
Step 1: Install the package #
sudo apt update
sudo apt install -y nginx
sudo systemctl enable --now nginx
nginx -v
Step 2: Open only the required ports #
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
sudo ufw status verbose
Always allow SSH before enabling the firewall, or you can lock yourself out of the server.
Step 3: Add security headers #
Create a snippet you can include in every server block:
# /etc/nginx/snippets/security-headers.conf
add_header X-Content-Type-Options 'nosniff' always;
add_header X-Frame-Options 'SAMEORIGIN' always;
add_header Referrer-Policy 'strict-origin-when-cross-origin' always;
add_header Permissions-Policy 'camera=(), microphone=(), geolocation=()' always;
Step 4: Hide the version and test #
# /etc/nginx/nginx.conf (inside the http block)
server_tokens off;
# then validate and reload
sudo nginx -t && sudo systemctl reload nginx
Troubleshooting checklist #
- Port already in use: run
sudo ss -tlnp | grep :80to find the other service. - Config test fails: read the line number in the error and fix that block first.
- 502 Bad Gateway: confirm PHP-FPM is running and the socket path matches
fastcgi_pass.