Learn how to install Nginx on Ubuntu, Debian, AlmaLinux, Rocky Linux and Fedora, then set up your first server block to host a static website. Covers directory structure, systemctl management and firewall configuration.
Prerequisites
- A server running Ubuntu, Debian, AlmaLinux, Rocky Linux or Fedora with root or sudo access
- A domain name pointed at your server, or willingness to test with an IP address
- Basic familiarity with the Linux command line
What this solves
This tutorial walks you through installing Nginx and creating your first virtual host, called a server block in Nginx terminology, to serve a static HTML website. You will learn the directory structure, how to manage the service with systemctl, and how to troubleshoot common problems.
By the end you will have a working Nginx installation serving a custom domain, with a verified configuration and an open firewall port for HTTP traffic.
Step-by-step installation
Update your package manager
Always update your package index before installing new software so you get the latest available version and security patches.
sudo apt update && sudo apt upgrade -ysudo dnf upgrade -yInstall Nginx
This installs the Nginx package along with its default configuration files and a systemd service unit.
sudo apt install -y nginxsudo dnf install -y nginxStart and enable the service
Starting the service launches Nginx immediately. Enabling it ensures Nginx starts automatically on every reboot.
sudo systemctl enable --now nginxCheck that the service is active before moving on. You can read more about managing services in general in our guide on checking and managing running services on Linux with systemctl.
sudo systemctl status nginxUnderstand the Nginx directory structure
On Debian and Ubuntu, Nginx splits configuration into two directories: /etc/nginx/sites-available holds all defined server blocks, and /etc/nginx/sites-enabled contains symlinks to the ones that are actually active. This lets you keep a config file on disk without it being loaded.
On AlmaLinux, Rocky Linux and Fedora, Nginx instead uses /etc/nginx/conf.d, where any file ending in .conf is loaded automatically. There is no separate enable step on these distros.
ls -la /etc/nginx//etc/nginx/nginx.conf includes these directories with an include directive. Do not remove that line or your server blocks will stop loading.Create the web root directory
Create a dedicated directory for your site's files, separate from the default Nginx welcome page. Using a per-site directory under /var/www is the standard convention and keeps multiple sites organized.
sudo mkdir -p /var/www/example.com/htmlSet correct ownership so Nginx's worker process can read the files. On Debian and Ubuntu the Nginx user is www-data. On AlmaLinux, Rocky and Fedora it is nginx.
sudo chown -R www-data:www-data /var/www/example.com/html
sudo chmod -R 755 /var/www/example.com/htmlsudo chown -R nginx:nginx /var/www/example.com/html
sudo chmod -R 755 /var/www/example.com/htmlCreate a test HTML file
Add a simple HTML page so you have something to verify once the server block is live.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example.com</title>
</head>
<body>
<h1>It works! Nginx is serving example.com</h1>
</body>
</html>Create your first server block
A server block tells Nginx which domain to respond to, where its files live, and which port to listen on. On Debian and Ubuntu, create a new file in sites-available.
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;
}
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
}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;
}
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
}Enable the server block (Debian and Ubuntu only)
On Debian and Ubuntu you need to symlink the file into sites-enabled to activate it. AlmaLinux, Rocky and Fedora load everything in conf.d automatically, so this step does not apply there.
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/It is good practice to remove the default server block once you have your own configured, to avoid conflicting catch-all rules.
sudo rm -f /etc/nginx/sites-enabled/defaultTest the configuration syntax
Always test your configuration before reloading Nginx. This catches typos and syntax errors without taking the running server down.
sudo nginx -tA successful test prints syntax is ok and test is successful. If you see an error, it will point to the exact file and line number to fix.
Reload Nginx to apply changes
Reloading re-reads the configuration without dropping active connections, which is safer than a full restart.
sudo systemctl reload nginxOpen the firewall for HTTP traffic
If you have a firewall enabled, you need to explicitly allow port 80 for HTTP. Avoid disabling the firewall entirely, allow only the specific service you need.
sudo ufw allow 'Nginx HTTP'
sudo ufw reloadsudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --reloadFor a deeper look at crafting custom firewall rules beyond the basics, see our guide on implementing network security policies with iptables and firewalld.
Verify your setup
Confirm Nginx is running and listening on port 80.
sudo systemctl status nginx
sudo ss -tlnp | grep :80Test locally with curl, then from a browser using your server's public IP or domain, for example 203.0.113.10.
curl -I http://example.com
curl -I http://203.0.113.10You should see an HTTP/1.1 200 OK response and, in a browser, your test HTML page with the heading you wrote earlier.
Viewing access and error logs
Nginx writes two log files per site by default: an access log recording every request, and an error log recording problems. These are the first place to look when something is not working.
sudo tail -f /var/log/nginx/example.com.access.log
sudo tail -f /var/log/nginx/example.com.error.logIf you prefer a centralized view across multiple services, see our tutorial on setting up NGINX monitoring with Prometheus and Grafana once you are comfortable with the basics.
Common issues
| Symptom | Cause | Fix |
|---|---|---|
| 403 Forbidden in browser | Wrong ownership or missing execute permission on parent directories | Run sudo chown -R www-data:www-data /var/www/example.com and ensure directories are 755, never chmod 777 |
| Default Nginx page still shows instead of your site | Default server block still enabled, or server_name mismatch | Remove /etc/nginx/sites-enabled/default and confirm server_name matches the domain you are testing |
| nginx -t fails with unexpected token | Missing semicolon or unmatched brace in server block | Re-check the file named in the error output, fix syntax, rerun sudo nginx -t |
| Connection refused from outside the server | Firewall blocking port 80 | Allow HTTP with ufw or firewalld as shown above |
| Changes to HTML not appearing | Browser cache or wrong root path in server block | Hard refresh the browser and confirm root directive points to the correct directory |
| Service fails to start | Another process already bound to port 80 | Check with sudo ss -tlnp | grep :80, stop the conflicting service |
Next steps
- Configure NGINX SSL termination with Certbot
- Configure NGINX virtual hosts with SSL certificates for multiple domains
- Set up NGINX rate limiting and security headers safely
- Configure NGINX reverse proxy with load balancing and SSL termination
- Find and kill processes using a specific port on Linux
Running this in production?
Automated install script
Run this to automate the entire setup
#!/usr/bin/env bash
set -euo pipefail
# ---------------------------------------------------------------------------
# Nginx virtual host (server block) installer
# Usage: sudo ./install_nginx_vhost.sh <domain> [document_root]
# ---------------------------------------------------------------------------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
log() { echo -e "${GREEN}[OK]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
error() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
usage() {
echo "Usage: $0 <domain> [document_root]"
echo "Example: $0 example.com /var/www/example.com/html"
exit 1
}
# ---------------------------------------------------------------------------
# Argument validation
# ---------------------------------------------------------------------------
if [ "$#" -lt 1 ] || [ "$#" -gt 2 ]; then
usage
fi
DOMAIN="$1"
WEBROOT="${2:-/var/www/${DOMAIN}/html}"
if ! [[ "$DOMAIN" =~ ^[A-Za-z0-9.-]+$ ]]; then
error "Invalid domain name: $DOMAIN"
usage
fi
# ---------------------------------------------------------------------------
# Root check
# ---------------------------------------------------------------------------
if [ "$(id -u)" -ne 0 ]; then
error "This script must be run as root or with sudo."
exit 1
fi
TOTAL_STEPS=9
STEP=0
step() {
STEP=$((STEP + 1))
echo -e "${GREEN}[${STEP}/${TOTAL_STEPS}]${NC} $*"
}
# ---------------------------------------------------------------------------
# Rollback on failure
# ---------------------------------------------------------------------------
CONF_FILE=""
cleanup_on_error() {
error "Installation failed. Rolling back changes..."
[ -n "$CONF_FILE" ] && [ -f "$CONF_FILE" ] && rm -f "$CONF_FILE"
if [ -n "${SITES_ENABLED_LINK:-}" ] && [ -L "$SITES_ENABLED_LINK" ]; then
rm -f "$SITES_ENABLED_LINK"
fi
exit 1
}
trap cleanup_on_error ERR
# ---------------------------------------------------------------------------
# Step 1: Detect distro
# ---------------------------------------------------------------------------
step "Detecting operating system..."
if [ -f /etc/os-release ]; then
. /etc/os-release
case "$ID" in
ubuntu|debian)
PKG_MGR="apt"
PKG_INSTALL="apt install -y"
WEB_USER="www-data"
NGINX_USER_GROUP="www-data"
CONF_STYLE="sites"
FIREWALL="ufw"
;;
almalinux|rocky|centos|rhel|ol|fedora)
PKG_MGR="dnf"
PKG_INSTALL="dnf install -y"
WEB_USER="nginx"
NGINX_USER_GROUP="nginx"
CONF_STYLE="confd"
FIREWALL="firewalld"
;;
amzn)
PKG_MGR="yum"
PKG_INSTALL="yum install -y"
WEB_USER="nginx"
NGINX_USER_GROUP="nginx"
CONF_STYLE="confd"
FIREWALL="firewalld"
;;
*)
error "Unsupported distro: $ID"
exit 1
;;
esac
log "Detected distro: $ID (package manager: $PKG_MGR)"
else
error "/etc/os-release not found. Cannot detect distro."
exit 1
fi
# ---------------------------------------------------------------------------
# Step 2: Update package index
# ---------------------------------------------------------------------------
step "Updating package index..."
if [ "$PKG_MGR" = "apt" ]; then
apt update -y
else
$PKG_MGR check-update -y || true # check-update returns 100 if updates exist, ignore
fi
# ---------------------------------------------------------------------------
# Step 3: Install Nginx
# ---------------------------------------------------------------------------
step "Installing Nginx..."
if command -v nginx >/dev/null 2>&1; then
warn "Nginx is already installed, skipping installation."
else
$PKG_INSTALL nginx
fi
# ---------------------------------------------------------------------------
# Step 4: Start and enable service
# ---------------------------------------------------------------------------
step "Starting and enabling Nginx service..."
systemctl enable --now nginx
if ! systemctl is-active --quiet nginx; then
error "Nginx service failed to start."
exit 1
fi
log "Nginx service is active."
# ---------------------------------------------------------------------------
# Step 5: Create web root and test page
# ---------------------------------------------------------------------------
step "Creating web root at $WEBROOT..."
mkdir -p "$WEBROOT"
cat > "${WEBROOT}/index.html" <<EOF
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>${DOMAIN}</title>
</head>
<body>
<h1>It works! Nginx is serving ${DOMAIN}</h1>
</body>
</html>
EOF
# Correct ownership and minimal permissions (never 777/666)
chown -R "${NGINX_USER_GROUP}:${NGINX_USER_GROUP}" "/var/www/${DOMAIN}"
find "/var/www/${DOMAIN}" -type d -exec chmod 755 {} \;
find "/var/www/${DOMAIN}" -type f -exec chmod 644 {} \;
log "Web root created and permissions set."
# ---------------------------------------------------------------------------
# Step 6: Create server block
# ---------------------------------------------------------------------------
step "Creating Nginx server block for ${DOMAIN}..."
if [ "$CONF_STYLE" = "sites" ]; then
mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled
CONF_FILE="/etc/nginx/sites-available/${DOMAIN}.conf"
SITES_ENABLED_LINK="/etc/nginx/sites-enabled/${DOMAIN}.conf"
else
CONF_FILE="/etc/nginx/conf.d/${DOMAIN}.conf"
fi
cat > "$CONF_FILE" <<EOF
server {
listen 80;
listen [::]:80;
server_name ${DOMAIN} www.${DOMAIN};
root ${WEBROOT};
index index.html;
location / {
try_files \$uri \$uri/ =404;
}
access_log /var/log/nginx/${DOMAIN}.access.log;
error_log /var/log/nginx/${DOMAIN}.error.log;
}
EOF
chmod 644 "$CONF_FILE"
if [ "$CONF_STYLE" = "sites" ]; then
ln -sf "$CONF_FILE" "$SITES_ENABLED_LINK"
fi
log "Server block written to $CONF_FILE"
# ---------------------------------------------------------------------------
# Step 7: Test configuration and reload
# ---------------------------------------------------------------------------
step "Testing Nginx configuration..."
if ! nginx -t; then
error "Nginx configuration test failed."
exit 1
fi
systemctl reload nginx
log "Nginx configuration test passed and service reloaded."
# ---------------------------------------------------------------------------
# Step 8: Open firewall port for HTTP
# ---------------------------------------------------------------------------
step "Configuring firewall for HTTP traffic..."
if [ "$FIREWALL" = "ufw" ]; then
if command -v ufw >/dev/null 2>&1; then
if ufw status | grep -q "Status: active"; then
ufw allow 'Nginx HTTP' || ufw allow 80/tcp
log "UFW rule added for port 80."
else
warn "UFW is installed but inactive. Skipping firewall rule."
fi
else
warn "UFW not installed. Skipping firewall configuration."
fi
elif [ "$FIREWALL" = "firewalld" ]; then
if command -v firewall-cmd >/dev/null 2>&1 && systemctl is-active --quiet firewalld; then
firewall-cmd --permanent --add-service=http
firewall-cmd --reload
log "firewalld rule added for HTTP service."
else
warn "firewalld not active. Skipping firewall configuration."
fi
fi
# ---------------------------------------------------------------------------
# Step 9: Final verification
# ---------------------------------------------------------------------------
step "Verifying installation..."
if ! systemctl is-active --quiet nginx; then
error "Nginx is not running after setup."
exit 1
fi
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" -H "Host: ${DOMAIN}" http://127.0.0.1/ || echo "000")
if [ "$HTTP_CODE" = "200" ]; then
log "Verification succeeded: received HTTP 200 for ${DOMAIN}."
else
warn "Verification returned HTTP ${HTTP_CODE}. Check DNS, firewall, and config manually."
fi
trap - ERR
echo
log "Installation complete."
echo "Domain: ${DOMAIN}"
echo "Web root: ${WEBROOT}"
echo "Config file: ${CONF_FILE}"
echo "Next steps: point your domain's DNS A record to this server's IP,"
echo "and consider adding HTTPS with certbot for production use."
Review the script before running. Execute with: bash install.sh