How To Install Nginx on Ubuntu 26.04 LTS

Install Nginx on Ubuntu 26.04 LTS

Ubuntu 26.04 LTS is out, and sooner or later a fresh VPS lands in your lap with an empty prompt and a deadline. The web server has to be up before lunch. Nginx is the usual answer, and for good reason. It is light on memory, handles thousands of concurrent connections without drama, and works equally well as a static file server, a reverse proxy, or a TLS terminator in front of an application.

Installing it takes one command. That is the easy part, and it is also where most tutorials stop. The trouble starts later. A default config that quietly leaks the version string. A firewall that blocks port 80 while the service reports “active (running)”. A package from the Ubuntu archive that is a full release branch behind what the vendor ships. A worker_connections value that looked fine until the first traffic spike.

This guide covers the whole path. It starts with the install, with two methods and an honest look at which one fits which situation. Then it moves to the firewall, server blocks, HTTPS, hardening, performance tuning, and the errors that show up in real logs. Every command was written with Ubuntu 26.04 “Resolute Raccoon” in mind. Most of them also work on Debian 12 and 13. Where AlmaLinux behaves differently, that is noted.

What You Need Before Starting

Keep the prerequisites short and real:

  • A server running Ubuntu 26.04 LTS. The 26.04.1 point release is already listed on the official Ubuntu releases page.
  • A non-root user with sudo rights. Running everything as root is a habit worth dropping.
  • A domain name pointing at the server’s public IP, if you plan to enable HTTPS. An A record is enough, and an AAAA record helps if you have IPv6.
  • Ports 80 and 443 reachable from the internet. Cloud providers often add their own security group on top of the OS firewall, and that catches people out all the time.

Check the release before touching anything:

lsb_release -a
uname -r

If the output says 26.04 and resolute, carry on.

Which Nginx Version Should Be Installed?

Pick the source before running any install command. Switching later means removing packages, rewriting repo files, and hoping the config survives.

Option 1: The Ubuntu Archive Package

This is the default and the lowest-maintenance choice. The nginx package in Ubuntu’s own repositories is patched and maintained by Ubuntu’s security team, and it follows the distribution’s conventions. Guides written for 26.04 show it reporting nginx 1.28.3. The archive entry for resolute lists 1.28.3-2ubuntu1.14, published on 20 November 2026.

That version number looks old next to upstream, but the Ubuntu build gets security fixes backported. The archive page even mentions HTTP/3-related advisories being addressed in the package. For a typical business site, a WordPress box, or an internal tool, this is the right pick.

Option 2: The Official nginx.org Repository

Upstream publishes its own packages in two flavors. Mainline gets new features. Stable gets only important fixes. As of the most recent upstream release on 23 November 2026, the stable branch is 1.30.8 and the mainline branch is 1.31.10. The official packages page lists 26.04 “resolute” as a supported platform on both x86_64 and arm64.

Choose this route when you need a feature the Ubuntu build lacks, or when your compliance team insists on the vendor’s package. The trade-off is that you own the update cadence. There is also a layout difference, covered in the troubleshooting section, which surprises almost everyone who switches.

Factor Ubuntu archive nginx.org stable nginx.org mainline
Version (late Nov 2026) 1.28.3 with backports 1.30.8 1.31.10
Config layout sites-available / sites-enabled conf.d only conf.d only
Patch source Ubuntu security team Upstream Upstream
Best for Most sites, LEMP stacks Teams wanting current features with low churn Testing, bleeding-edge needs
Risk of breaking changes Lowest Low Moderate

A practical rule: if nobody on the team can name a feature they need from a newer version, use the Ubuntu package. Boring wins in production.

Installing Nginx from the Ubuntu Repository

Start with a fresh package index and any pending upgrades. Skipping this step is how people end up pulling stale metadata.

sudo apt update
sudo apt upgrade -y

Then install:

sudo apt install nginx -y

APT pulls in the core package plus its dependencies, creates the www-data runtime user, drops a default config under /etc/nginx, and starts the service. On Ubuntu, services start automatically after installation. That is convenient, and it also means a half-configured web server is listening on port 80 the moment the install finishes.

Verify the version:

nginx -v

For a more complete picture, including compile-time flags and modules, use the capital V:

nginx -V 2>&1 | tr ' ' '\n' | grep -E 'with-http|with-stream' | head -30

That second command is a quick way to see which modules are built in. It saves a lot of guessing when someone asks whether http_v2_module or stream_ssl_module is available.

Installing Nginx from the Official nginx.org Repo

Skip this section if the Ubuntu package suits you. Otherwise, follow it closely. The steps mirror the official installation instructions for Ubuntu.

First, install the prerequisites:

sudo apt install curl gnupg2 ca-certificates lsb-release ubuntu-keyring -y

Import the signing key into a dedicated keyring. Putting it in /usr/share/keyrings rather than the legacy global trusted store limits what that key can sign.

curl -fsSL https://nginx.org/keys/nginx_signing.key \
  | gpg --dearmor \
  | sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

Check that the key fingerprint matches what nginx.org publishes. This is the step people skip, and it is the one that matters:

gpg --dry-run --quiet --no-keyring --import --import-options import-show \
  /usr/share/keyrings/nginx-archive-keyring.gpg

Now add the repository. This example uses the stable branch:

echo "deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \
http://nginx.org/packages/ubuntu $(lsb_release -cs) nginx" \
  | sudo tee /etc/apt/sources.list.d/nginx.list

For mainline, change packages/ubuntu to packages/mainline/ubuntu.

Here is the part that bites. Ubuntu’s own nginx package can outrank the vendor one depending on version numbers, so APT might quietly pick the wrong source. Pin the nginx.org repo with higher priority:

echo -e "Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n" \
  | sudo tee /etc/apt/preferences.d/99nginx

Update, confirm where the candidate comes from, then install:

sudo apt update
apt-cache policy nginx
sudo apt install nginx -y

Read the apt-cache policy output. The candidate should show a version ending in ~resolute from nginx.org. At the time of writing, the stable build in that repo is 1.30.8-1~resolute. If the candidate still points at an Ubuntu version, the pin did not take effect.

A word of caution on mixing. Do not install the Ubuntu package first and then bolt on the vendor repo and run apt upgrade, unless you have planned the switch. The config layout differences can leave you with virtual hosts that silently stop loading.

Starting, Enabling, and Checking the Service

Ubuntu uses systemd, so everything runs through systemctl:

sudo systemctl enable --now nginx
sudo systemctl status nginx --no-pager

The enable --now combination does two jobs at once. It makes Nginx start on boot and starts it immediately. You want both. A server that reboots after a kernel update and comes back without its web server is an embarrassing 3 a.m. page.

Day-to-day commands worth memorizing:

sudo systemctl reload nginx     # apply config changes without dropping connections
sudo systemctl restart nginx    # full stop/start, use sparingly
sudo systemctl stop nginx
sudo nginx -t                   # test config syntax
sudo nginx -T | less            # dump the full merged configuration

Reload, not restart, is the default habit. A reload spawns new workers with the new config and lets old workers finish in-flight requests. A restart kills connections. On a busy site, that difference shows up in your error rate.

Always run nginx -t first. Always. A reload with a syntax error is safe because Nginx keeps the old config, but a restart with the same error leaves the service down.

Opening the Firewall with UFW

Ubuntu ships with UFW, a friendly front end to the kernel packet filter. It is usually inactive on a new cloud image. Turn it on carefully, because enabling it without allowing SSH locks you out of your own machine.

sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
sudo ufw status verbose

The Nginx package registers three application profiles. You can list them:

sudo ufw app list
  • Nginx HTTP opens only port 80.
  • Nginx HTTPS opens only port 443.
  • Nginx Full opens both.

Once HTTPS is working and HTTP is only used for redirects, you still need port 80 open. Let’s Encrypt validation and the redirect itself both depend on it. Leave it alone.

On AlmaLinux, the equivalent is firewalld:

sudo firewall-cmd --permanent --add-service=http --add-service=https
sudo firewall-cmd --reload

Now test from outside the server. From your laptop:

curl -I http://YOUR_SERVER_IP

A 200 OK response with a Server: nginx header tells you the whole path works. Opening the IP in a browser should show the default “Welcome to nginx!” page.

Understanding the File Layout

Knowing where things live saves time during every incident. On the Ubuntu package:

  • /etc/nginx/nginx.conf is the main configuration file.
  • /etc/nginx/sites-available/ holds virtual host definitions.
  • /etc/nginx/sites-enabled/ holds symlinks to the ones that are live.
  • /etc/nginx/conf.d/ is for additional snippets, loaded automatically.
  • /etc/nginx/snippets/ holds reusable fragments you include by hand.
  • /var/www/html/ is the default document root.
  • /var/log/nginx/access.log and error.log are the logs.

The sites-available and sites-enabled pattern is a Debian convention, not an Nginx one. It lets you disable a site by removing a symlink instead of deleting a file. The nginx.org packages skip that convention and load everything from conf.d/*.conf. Neither is wrong. They are just different, and tutorials often forget to say which one they assume.

Creating a Server Block for Your Domain

A server block is Nginx’s term for a virtual host. Running one site per server is increasingly rare, so get comfortable with this pattern from the start.

Create the web root and give it sensible ownership:

sudo mkdir -p /var/www/example.com/html
sudo chown -R $USER:www-data /var/www/example.com
sudo find /var/www/example.com -type d -exec chmod 755 {} \;
sudo find /var/www/example.com -type f -exec chmod 644 {} \;

Why those permissions? Directories need the execute bit so the worker can traverse them. Files only need to be readable. Giving the web server write access to the document root is a classic mistake. If an application bug lets an attacker upload a file, writable roots turn a minor flaw into a full compromise.

Add a test page:

echo '<h1>example.com is alive</h1>' > /var/www/example.com/html/index.html

Now write the config:

sudo nano /etc/nginx/sites-available/example.com
server {
    listen 80;
    listen [::]:80;

    server_name example.com www.example.com;

    root /var/www/example.com/html;
    index index.html index.htm;

    access_log /var/log/nginx/example.com.access.log;
    error_log  /var/log/nginx/example.com.error.log warn;

    location / {
        try_files $uri $uri/ =404;
    }
}

Enable it, test, reload:

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Per-site log files are worth the small effort. When a client says “the site was slow yesterday at 14:00,” a dedicated log makes that question answerable in a minute instead of an hour.

One more cleanup: the default site is still enabled and will answer requests that do not match any server_name. That is acceptable, but a stricter approach is a catch-all that drops unknown hosts:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    return 444;
}

Status 444 is an Nginx-specific code that closes the connection without a response. Bots scanning by IP address get nothing useful, and your logs stay cleaner.

Enabling HTTPS with Let’s Encrypt

Plain HTTP in 2026 is a non-starter. Browsers flag it, search engines weigh it, and credentials sent over it are readable by anyone on the path. Certbot is still the most common way to get free certificates.

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com

Certbot edits the server block, adds the certificate paths, and sets up an HTTP to HTTPS redirect. Check the renewal timer afterwards:

systemctl list-timers | grep certbot
sudo certbot renew --dry-run

Do not skip the dry run. Renewal failures are quiet. The first symptom is usually a browser warning ninety days later.

If you prefer to write the TLS block by hand, here is a clean modern baseline:

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    http2 on;

    server_name example.com www.example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;

    ssl_stapling on;
    ssl_stapling_verify on;

    root /var/www/example.com/html;
    index index.html;
}

The standalone http2 on; directive replaced the older listen 443 ssl http2; form in recent Nginx releases, and the old syntax now triggers deprecation warnings. Both Ubuntu’s 1.28 and the upstream branches accept the newer one.

Keep an eye on TLS-related advisories. The 23 November 2026 upstream release fixed excessive CPU usage when ssl_early_data is enabled. If you turned on 0-RTT early data for speed, check whether your build is patched, or switch the directive off until it is.

Security Hardening That Actually Matters

Hardening guides can read like a wish list. These are the changes that make a measurable difference.

Patch Quickly, and Know Your Exposure

Nginx’s recent history is a reminder that web servers are a target. The 18 November 2026 upstream release bundled fixes for a long list of issues, including use-after-free bugs in the resolver, HTTP/2 and HTTP/3 code, memory corruption in HTTP/2 flow control, and a buffer overflow involving alias with try_files. Which of those affect you depends on your config. Servers without HTTP/3 enabled, for instance, are not exposed to the HTTP/3 flaws.

Set up unattended security upgrades so you are not relying on memory:

sudo apt install unattended-upgrades -y
sudo dpkg-reconfigure --priority=low unattended-upgrades

If you use the nginx.org repo, remember that Ubuntu’s automatic updates cover only the Ubuntu origins by default. Add the nginx.org origin to the allowed list in /etc/apt/apt.conf.d/50unattended-upgrades, or schedule manual patch windows.

Hide the Version Number

http {
    server_tokens off;
}

This will not stop a determined attacker. It does stop the lazy scanner that greps for specific version strings, and that covers most of the automated noise.

Add Security Headers

Put these in a snippet so every server block can reuse them:

sudo nano /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 Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Then include it inside each HTTPS server block:

include snippets/security-headers.conf;

A gotcha worth knowing: add_header directives are inherited only if the current block defines none of its own. Add one header inside a location and the inherited set vanishes for that location. This breaks header scoring quietly, and people lose hours chasing it.

Be careful with HSTS. Once a browser has seen it, it refuses plain HTTP for the stated period. Test with a short max-age first.

Block Hidden Files and Limit Methods

location ~ /\.(?!well-known) {
    deny all;
}

if ($request_method !~ ^(GET|HEAD|POST)$ ) {
    return 405;
}

The first rule stops requests for .git, .env, and .htaccess, which scanners probe constantly. The .well-known exception keeps Let’s Encrypt validation working. Many a certificate renewal has broken because someone wrote deny all for every dotfile.

Rate Limiting

For login pages and APIs, throttle at the edge:

http {
    limit_req_zone $binary_remote_addr zone=login:10m rate=5r/s;
}

server {
    location /wp-login.php {
        limit_req zone=login burst=10 nodelay;
    }
}

This is cheap insurance against credential stuffing. It will not stop a distributed attack, but it handles the single-IP brute force that makes up most of the traffic.

Tools Worth Installing

  • fail2ban bans IPs that repeatedly hit error patterns in your logs.
  • lynis runs a broad system audit and gives a prioritized list.
  • ss -tulpn shows what is listening and which process owns it.
  • testssl.sh or the SSL Labs scanner grades your TLS configuration.

Performance Tuning for Real Traffic

Defaults are written to be safe on a tiny machine. Production boxes deserve better. Open /etc/nginx/nginx.conf and work through these areas.

CPU and Workers

user www-data;
worker_processes auto;
worker_rlimit_nofile 65535;

events {
    worker_connections 4096;
    multi_accept on;
}

worker_processes auto matches the number of CPU cores, which is nearly always correct. Setting it higher than core count just adds context switching. Total theoretical capacity is roughly workers multiplied by worker_connections, but each proxied request uses two connections, one to the client and one to the upstream. Plan for that.

The worker_rlimit_nofile line matters more than people think. Each connection consumes a file descriptor. If the OS limit is lower than what Nginx wants, you will see “Too many open files” in the error log right when traffic peaks. For systemd-managed services, also raise the limit at the unit level:

sudo systemctl edit nginx
[Service]
LimitNOFILE=65535

Then run sudo systemctl daemon-reload && sudo systemctl restart nginx.

Memory and Buffers

http {
    client_body_buffer_size 16k;
    client_max_body_size 20m;
    client_header_buffer_size 2k;
    large_client_header_buffers 4 8k;
}

Keep these modest. Oversized buffers multiply by the number of connections, and RAM disappears faster than expected. Raise client_max_body_size only as far as your application needs for uploads. The default of 1 MB is the usual reason a CMS upload fails with a 413 error.

Compression and Static Files

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    gzip on;
    gzip_comp_level 5;
    gzip_min_length 1024;
    gzip_vary on;
    gzip_types text/plain text/css application/json application/javascript
               application/xml image/svg+xml;
}

sendfile lets the kernel copy file data straight to the socket without passing through user space, which cuts CPU use on static content. A gzip level around 5 is the sweet spot. Going to 9 burns CPU for a tiny extra reduction in size. Never gzip already-compressed formats such as JPEG, PNG, or MP4.

Cache static assets aggressively:

location ~* \.(?:css|js|woff2|jpg|jpeg|png|gif|svg|webp|avif|ico)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
    access_log off;
}

Turning off access logging for static files also lowers disk writes, which matters on cloud volumes with throttled IOPS.

Disk I/O

Logging is the hidden I/O cost on busy servers. Buffer it:

access_log /var/log/nginx/access.log combined buffer=64k flush=5s;

Make sure logrotate is working, since a runaway log file can fill the root partition and take the whole server with it. Ubuntu installs a rotation rule for Nginx by default. Check it at /etc/logrotate.d/nginx. For open file cache on large static sites:

open_file_cache max=10000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;

Network and Kernel Settings

For high-concurrency servers, a few sysctl tweaks help:

sudo tee /etc/sysctl.d/99-nginx.conf <<'EOF'
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 4096
net.ipv4.ip_local_port_range = 10240 65535
net.ipv4.tcp_tw_reuse = 1
EOF
sudo sysctl --system

Then match it in the listen directive with listen 443 ssl backlog=4096;. Raising the Nginx backlog without raising somaxconn does nothing, because the kernel caps it.

Reverse Proxy and Keepalive

When fronting an app server such as Node, Gunicorn, or PHP-FPM, reuse upstream connections:

upstream app_backend {
    server 127.0.0.1:3000;
    keepalive 32;
}

location / {
    proxy_pass http://app_backend;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

Without keepalive, every request opens a fresh TCP connection to the backend. Under a traffic spike, that means a flood of sockets in TIME_WAIT and a backend that spends its time on handshakes.

A Real-World Scenario: The Traffic Spike

Picture a marketing email going out to 200,000 subscribers at 9:00. By 9:03 the site is crawling. What happens in practice?

Usually it is not Nginx itself. The error log shows worker_connections are not enough or upstream timeouts. The first step is ss -s for socket counts, then tail -f /var/log/nginx/error.log, then checking top or htop for the backend process. If PHP-FPM or the app is saturated, Nginx is simply reporting the problem.

The fastest relief is FastCGI or proxy caching for anonymous traffic:

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=appcache:50m
                 max_size=1g inactive=60m use_temp_path=off;

location / {
    proxy_cache appcache;
    proxy_cache_valid 200 301 10m;
    proxy_cache_use_stale error timeout updating http_500 http_502 http_503;
    proxy_cache_lock on;
    add_header X-Cache-Status $upstream_cache_status;
    proxy_pass http://app_backend;
}

The proxy_cache_use_stale and proxy_cache_lock lines are the heroes here. Stale content gets served while the backend recovers, and only one request per key goes to the origin during a cache miss. Even a 10 minute cache can turn a thousand requests per second against the app into a handful.

Troubleshooting Common Nginx Errors

Every administrator hits these. Here is how to diagnose each one without guessing.

“nginx: [emerg] bind() to 0.0.0.0:80 failed (98: Address already in use)”

Something else owns the port. Often it is Apache, left over from a previous setup.

sudo ss -tulpn | grep ':80'
sudo systemctl stop apache2
sudo systemctl disable apache2

403 Forbidden

Three usual suspects: missing index file, wrong permissions, or the worker user cannot traverse a parent directory. Check the path:

namei -l /var/www/example.com/html/index.html

That command prints permissions for every directory in the chain. A single parent folder with mode 700 will break everything below it. Also look for SELinux issues on AlmaLinux, where restorecon -Rv /var/www often fixes the context.

404 on Pages That Should Exist

Check root versus alias. They behave differently with trailing paths, and mixing them up is a frequent mistake. For single-page apps, use try_files $uri /index.html; so client-side routes do not return a 404.

502 Bad Gateway

Nginx reached for the upstream and found nothing. Is the backend running? Is the socket path right? Is it a permissions problem on a Unix socket?

sudo systemctl status php8.4-fpm
sudo tail -n 50 /var/log/nginx/error.log

Adjust the PHP-FPM service name to match your installed version.

504 Gateway Timeout

The backend is alive but slow. Raising timeouts is tempting. Fix the slow query first, and only extend proxy_read_timeout or fastcgi_read_timeout as a stopgap.

413 Request Entity Too Large

Raise client_max_body_size, and remember PHP has its own upload_max_filesize and post_max_size limits. Both layers need to agree.

Config Test Passes but the Site Does Not Load

Check the firewall and the cloud provider’s security group before the config. From outside, curl -v http://IP tells you whether it is a timeout (filtered), a refusal (nothing listening), or an HTTP response (config).

“Welcome to nginx” Shows Instead of Your Site

The server_name does not match the request, or the symlink is missing. Dump the live config:

sudo nginx -T | grep -E 'server_name|listen'

Sites Vanish After Switching to nginx.org Packages

Those packages do not read sites-enabled. Move your files into /etc/nginx/conf.d/ with a .conf extension, or add include /etc/nginx/sites-enabled/*; to the http block yourself.

r00t is a Server System Administrator with more than 7 years of experience in server administration, operating systems, and programming. They have a strong track record of managing, securing, and optimizing Linux-based infrastructure (Ubuntu, Debian, CentOS/AlmaLinux) as well as Windows Server, across on-premises, VPS, and cloud environments. Their expertise covers configuring and maintaining web servers (Nginx, Apache) and databases (MySQL/MariaDB, PostgreSQL). It also includes virtualization and containers (Proxmox, Docker), networking, firewalls, and security hardening. They are experienced in monitoring, backup and disaster recovery, and troubleshooting to keep services available and performing well. Skilled in Bash, Python, and PHP, they automate routine tasks, build maintenance scripts, and manage deployments, which makes operations more efficient and less error-prone. They are known for being meticulous, responsive during incidents, and willing to share knowledge with teams and the wider community. Outside of work, r00t enjoys experimenting with homelabs, open source software, and emerging infrastructure technologies.

Related Posts