Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Install Nginx on Ubuntu

By Kokil Thapa | Last reviewed: September 2026

You need a fast, predictable web server before any Laravel app, WordPress site, or API goes live. To install Nginx on Ubuntu, you use the official Ubuntu packages, enable the service with systemd, and then layer site configs, PHP-FPM, and TLS on top. I deploy Nginx on Ubuntu 22.04 and 24.04 VPS instances weekly for client projects, often as the front end of a LEMP stack on Ubuntu. This guide walks through a clean install, a working default site, and the production hardening steps I apply before traffic hits the box.

How do you install Nginx on Ubuntu step by step?

Start on a fresh Ubuntu Server instance with SSH access and sudo privileges. If the box is brand new, follow a baseline Ubuntu server setup guide first—updates, a non-root sudo user, and SSH keys save pain later.

Update package indexes

Ubuntu ships Nginx in the default repositories for both 22.04 LTS and 24.04 LTS. Refresh indexes before you install anything.

sudo apt update
sudo apt upgrade -y

Install Nginx from the Ubuntu repository

The package name is simply nginx. No third-party PPA is required for most production PHP and static sites.

sudo apt install nginx -y

After installation, systemd registers the nginx unit. Verify it is active:

sudo systemctl status nginx
sudo systemctl enable nginx

You should see active (running). Visit the server IP in a browser. The default Ubuntu Nginx welcome page confirms the install worked.

Install Nginx on Ubuntu — Core Stepsapt updaterefresh indexesapt installnginx packagesystemctlenable + startPort 80welcome pageUFW allow80, 443/tcpSite configsites-availablenginx -tsyntax testProductionTLS + PHP-FPM
Install Nginx on Ubuntu: from package install through firewall, virtual host, and production TLS setup

Open firewall ports before testing remotely

UFW often blocks HTTP by default on hardened servers. Allow Nginx profiles or explicit ports.

sudo ufw allow 'Nginx Full'
sudo ufw status

For a manual rule set, see the dedicated guide on how to configure a firewall with UFW on Ubuntu. Port 80 serves plain HTTP. Port 443 serves HTTPS after you add certificates.

Understand key file locations

After you install Nginx on Ubuntu, these paths matter daily:

  • /etc/nginx/nginx.conf — global settings, worker processes, gzip, logging
  • /etc/nginx/sites-available/ — virtual host definitions you author
  • /etc/nginx/sites-enabled/ — symlinks to active site configs
  • /var/www/ — typical document root for web files
  • /var/log/nginx/access.log and error.log — first place to look when something breaks

The default site lives at /etc/nginx/sites-available/default. I usually disable it once a real vhost is ready.

Which Nginx version does Ubuntu ship, and is it enough for production?

Ubuntu LTS repositories track a stable Nginx release tested against that distro cycle. On Ubuntu 24.04 in 2026, you typically get Nginx 1.24.x. Ubuntu 22.04 may ship 1.18.x unless you enable newer packages through normal distro updates.

Check your exact version after install:

nginx -v
nginx -V

The capital -V flag prints compile-time modules. Confirm --with-http_ssl_module and --with-http_v2_module appear. They are standard on Ubuntu builds and required for modern TLS and HTTP/2.

Nginx on Ubuntu — Request PathClientbrowser / APINginxmaster + workersport 80 / 443Static filesPHP-FPMPHP 8.3+app logicReverse proxyNode / appMySQL 9.7database layer
How Nginx on Ubuntu routes static assets, PHP-FPM, and reverse-proxied upstreams in a typical LEMP stack

For most Laravel, Symfony, and WordPress deployments I maintain, the distro Nginx build is sufficient. You only need a custom build or upstream PPA when you require bleeding-edge modules or very specific compile flags. The official Nginx Linux packages documentation covers alternative install paths if you outgrow the Ubuntu repo version.

SourceVersion trackBest forTrade-off
Ubuntu apt (nginx)Distro-stable (1.18–1.24.x)Laravel, WordPress, Symfony, static sitesNot the newest upstream release on day one
nginx.org official repoMainline or stable branchTeams that need latest features fastYou own repo trust and upgrade timing
Custom compileWhatever you buildSpecial modules (rare in PHP hosting)High maintenance; easy to drift from security patches

My default recommendation for client VPS work in Nepal and abroad: use Ubuntu's package unless you have a documented reason not to. Predictable security updates beat chasing version numbers.

How do you configure Nginx for PHP, Laravel, or WordPress after install?

Installing Nginx alone serves static HTML. Real applications need a server block and, for PHP stacks, a running PHP-FPM pool. Install PHP first if you have not already—see the guide to install PHP on Ubuntu for PHP 8.3 or 8.5 alongside required extensions.

Create a document root and sample site file

sudo mkdir -p /var/www/example.com/public
sudo chown -R $USER:www-data /var/www/example.com
sudo chmod -R 775 /var/www/example.com

For Laravel, point the root at the public/ directory, not the project root. That single mistake exposes .env files to the internet.

Write a server block

Create /etc/nginx/sites-available/example.com:

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    root /var/www/example.com/public;
    index index.php index.html;

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

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.3-fpm.sock;
    }

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

Enable the site and reload:

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

The nginx -t step is non-negotiable. A syntax error during reload can take down every vhost on the server. I run it in every deploy script.

Wire up the database layer

A LEMP stack is incomplete without MySQL or MariaDB. Pair this install with the guide to install MySQL on Ubuntu when your app needs persistent storage. On production Laravel apps like Adventure Third Pole Trek, Nginx handles TLS termination and static assets while PHP-FPM runs the framework and MySQL stores bookings.

For a full stack walkthrough—including PHP tuning and permissions—read how to deploy Laravel on an Ubuntu VPS with Nginx. Symfony projects follow a similar pattern; see Symfony deployment on Ubuntu VPS step by step for framework-specific notes.

WordPress-specific considerations

WordPress on Nginx needs pretty permalinks via try_files and careful handling of wp-admin redirects. High-traffic WooCommerce stores benefit from Nginx's static-file efficiency. Compare approaches in the article on WordPress Nginx vs Apache for high-traffic sites.

How do you add SSL and harden Nginx on Ubuntu?

Plain HTTP is fine for a five-minute smoke test. Production sites need TLS, sane headers, and rate-aware logging. I treat hardening as part of the install checklist, not a later phase.

Issue certificates with Certbot

Let's Encrypt via Certbot is the standard path on Ubuntu:

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

Certbot edits your server block to add listen 443 ssl directives and redirect HTTP to HTTPS. Renewal runs through a systemd timer—verify with sudo systemctl status certbot.timer. The Certbot official instructions stay current with Ubuntu versions.

For cipher and protocol tuning beyond defaults, read TLS 1.3 vs 1.2 configuration for Nginx. Prefer TLS 1.2 and 1.3 only; disable legacy protocols.

Apply baseline security settings

Add these inside your server block or a shared snippet:

add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

client_max_body_size 32M;
server_tokens off;

Hide the Nginx version string with server_tokens off; in nginx.conf or per vhost. Limit upload size with client_max_body_size so a rogue POST cannot exhaust disk.

Layer system hardening next: Ubuntu security hardening, Fail2ban for Nginx, and server hardening for Ubuntu web servers cover SSH, intrusion blocking, and audit practices I use on shared EC2 hosts.

Nginx vs Apache on UbuntuNginx+ Event-driven, low RAM+ Fast static file serving+ Reverse proxy built-in− No .htaccess per dir− PHP via FPM onlyBest: Laravel, API, high trafficApache+ .htaccess overrides+ mod_php on older stacks+ Shared hosting friendly− Higher memory per conn− Slower static at scaleBest: legacy WP, .htaccess
Nginx vs Apache on Ubuntu: why most new PHP deployments choose Nginx with PHP-FPM in 2026

Still running Apache? Migration is straightforward if you plan redirects and vhost parity. Follow the Apache to Nginx migration guide before you cut DNS over. For a broader decision frame, see Nginx vs Apache for PHP sites in 2026.

Set up a reverse proxy when needed

Node.js apps, WebSocket services, and internal microservices often sit behind Nginx. A minimal proxy block looks like this:

location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    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;
}

Full patterns—including upstream health checks—are covered in how to set up a reverse proxy with Nginx.

How do you troubleshoot Nginx after installing it on Ubuntu?

Most post-install failures fall into a short list. Work through them in order before you rewrite configs.

  1. Service will not start: Run sudo nginx -t and read journalctl -u nginx -e. A missing semicolon in any enabled vhost blocks the entire daemon.
  2. 502 Bad Gateway on PHP pages: PHP-FPM is down or the socket path is wrong. Check sudo systemctl status php8.3-fpm and confirm the fastcgi_pass path matches /run/php/.
  3. 403 Forbidden: Nginx lacks read permission on the document root. Fix ownership with www-data group membership and directory execute bits.
  4. Connection refused externally: UFW, cloud security groups, or ISP port blocks. Verify sudo ss -tlnp | grep nginx shows 0.0.0.0:80.
  5. Wrong site served: The first matching server_name wins. Check for duplicate default_server directives and stale symlinks in sites-enabled/.
Nginx Troubleshooting FlowSite not loading?nginx -t fails?fix syntax firstSyntax OK?check UFW + ports502 error?restart PHP-FPM403 error?fix file permissionstail -f /var/log/nginx/error.log
Troubleshooting decision tree after you install Nginx on Ubuntu: syntax, firewall, PHP-FPM, and permissions

Validate JSON API responses during debugging with the free JSON formatter tool on this site. For server-side log review, tail -f /var/log/nginx/error.log while you reproduce the issue beats guessing.

If Nginx starts but performance degrades under load, check worker count in nginx.conf. The default worker_processes auto; suits most single-VPS setups. Tune worker_connections only after you measure actual concurrency. Speed work belongs in a separate pass—see speed up Ubuntu performance and speed optimization services when Core Web Vitals matter for SEO.

When you prefer hands-off infrastructure work, Linux system administration covers install, hardening, monitoring, and ongoing patches for Nepal-based and remote clients. Typical VPS hosting runs Rs 1,500–5,000/month (~USD 11–37) depending on provider and RAM—Nginx itself adds no licensing cost.

Key Takeaways

  • Run sudo apt install nginx on Ubuntu 22.04 or 24.04, then systemctl enable --now nginx to confirm the service is active.
  • Always test config with sudo nginx -t before systemctl reload nginx—one bad vhost can stop every site on the box.
  • Point Laravel and Symfony apps at the public/ directory and pass PHP requests to the correct PHP-FPM socket.
  • Open UFW ports 80 and 443, then add TLS with Certbot before you send production traffic.
  • Check error.log first for 502 and 403 errors; most issues are FPM downtime or file permissions.
  • Ubuntu's repo Nginx is production-ready for PHP stacks—custom builds are rarely worth the maintenance overhead.

People Also Ask

Does Ubuntu come with Nginx pre-installed?

No. Ubuntu Server ships without a web server by default. You install Nginx explicitly with apt install nginx. Ubuntu Desktop may have no server daemons enabled unless you add them yourself.

How do I restart Nginx on Ubuntu after changing config?

Test syntax with sudo nginx -t. If the output says "syntax is ok", apply changes with sudo systemctl reload nginx for a graceful reload. Use sudo systemctl restart nginx only when a full process restart is required.

Can I run Nginx and Apache on the same Ubuntu server?

Yes, but not both on port 80 simultaneously. A common pattern runs Nginx on 80/443 as a reverse proxy and Apache on an internal port like 8080. For new deployments, pick one server to reduce complexity.

Which Ubuntu version is best for Nginx in 2026?

Ubuntu 24.04 LTS is the current long-term choice with support through 2029. Ubuntu 22.04 LTS remains viable until 2027. Both ship Nginx in their default repositories and receive regular security updates.

Next steps after you install Nginx on Ubuntu

You now have a running web server, a clear path to PHP-FPM and TLS, and a troubleshooting checklist for the errors I see most often on production boxes. The natural sequence is LEMP completion, application deploy, then monitoring and backups. Read Ubuntu server monitoring and backup strategies before launch day.

If you want Nginx installed, hardened, and paired with Laravel or WordPress on a managed VPS, contact us for a scoped setup. You can also browse the full portfolio of production sites running on this stack, or start from the homepage for service overview.

Frequently Asked Questions

Start on a fresh Ubuntu 22.04 or 24.04 Server instance with SSH and sudo access. Run sudo apt update and sudo apt upgrade -y, then sudo apt install nginx -y. Confirm the service with sudo systemctl status nginx and enable it at boot with sudo systemctl enable nginx. Open ports 80 and 443 using sudo ufw allow 'Nginx Full', visit the server IP to see the default welcome page, then add your own vhost under /etc/nginx/sites-available/. Always run sudo nginx -t before sudo systemctl reload nginx.

Run sudo apt update, then sudo apt install nginx -y. Confirm with sudo systemctl status nginx and enable boot start with sudo systemctl enable nginx.

No. Ubuntu Server ships without a web server by default. Install Nginx explicitly with apt install nginx after running apt update.

Ubuntu LTS repositories ship stable Nginx builds tested for that release cycle. On Ubuntu 24.04 in 2026 you typically get Nginx 1.24.x; Ubuntu 22.04 may ship 1.18.x unless newer packages arrive through normal updates. Check with nginx -v and nginx -V to confirm SSL and HTTP/2 compile modules. For most Laravel, Symfony, and WordPress stacks I maintain, the distro build is sufficient. Custom builds or upstream repos are only worth it when you need bleeding-edge modules or specific compile flags.

Test syntax first with sudo nginx -t. If output says syntax is ok, apply changes with sudo systemctl reload nginx for a graceful reload. Use sudo systemctl restart nginx only when a full process restart is required. Skipping nginx -t is risky because one bad vhost in sites-enabled can stop the entire daemon and take down every site on the box.

UFW often blocks HTTP on hardened Ubuntu servers. Allow traffic with sudo ufw allow 'Nginx Full', which opens ports 80 and 443, then verify with sudo ufw status. Port 80 serves plain HTTP; port 443 serves HTTPS after you add certificates. If connections still fail externally, also check cloud provider security groups and ISP port blocks beyond UFW itself.

Key paths after install include /etc/nginx/nginx.conf for global settings like worker processes, gzip, and logging. Virtual hosts live in /etc/nginx/sites-available/ and activate via symlinks in /etc/nginx/sites-enabled/. Web files typically sit under /var/www/. When something breaks, start with /var/log/nginx/access.log and /var/log/nginx/error.log. The default site is /etc/nginx/sites-available/default, which I usually disable once a real vhost is ready.

Nginx adds zero licensing cost—it is free open-source software. You only pay for the VPS hosting it, typically Rs 1,500–5,000/month (~USD 11–37) depending on provider and RAM.

Nginx alone serves static HTML. Create a document root such as /var/www/example.com/public with www-data group ownership. For Laravel, point root at public/, not the project root, or you expose .env to the internet. Write a server block with try_files, pass PHP requests to fastcgi_pass unix:/run/php/php8.3-fpm.sock using snippets/fastcgi-php.conf, and deny dotfiles except .well-known. Enable the site with a symlink into sites-enabled, run sudo nginx -t, then sudo systemctl reload nginx.

Install Certbot with sudo apt install certbot python3-certbot-nginx -y, then run sudo certbot --nginx -d example.com -d www.example.com. Certbot edits your server block to add listen 443 ssl and redirect HTTP to HTTPS. Renewal runs through a systemd timer—verify with sudo systemctl status certbot.timer. Prefer TLS 1.2 and 1.3 only. Add baseline headers like X-Frame-Options, X-Content-Type-Options, and Referrer-Policy, set server_tokens off, and limit uploads with client_max_body_size.

Most new PHP deployments on Ubuntu choose Nginx with PHP-FPM because it handles static assets efficiently and performs predictably on a single VPS. Apache remains viable, but Nginx plus PHP-FPM is the pattern I deploy weekly for Laravel and WordPress stacks. Migration from Apache is straightforward if you plan redirects and vhost parity before cutting DNS over. For greenfield projects, running one web server reduces complexity.

Yes, but not both on port 80 simultaneously. A common pattern runs Nginx on ports 80 and 443 as a reverse proxy while Apache listens internally on something like 8080. For new deployments, pick one web server to reduce operational complexity. Mixing both without a clear proxy role creates port conflicts, duplicate vhost maintenance, and harder troubleshooting when traffic hits the wrong backend.

A 502 on PHP pages almost always means PHP-FPM is down or the fastcgi_pass socket path in your server block is wrong. Check sudo systemctl status php8.3-fpm and confirm the socket matches what exists under /run/php/. If Nginx itself will not start, run sudo nginx -t and read journalctl -u nginx -e—a missing semicolon in any enabled vhost blocks the entire daemon. Tail /var/log/nginx/error.log while reproducing the issue.

403 Forbidden usually means Nginx lacks read permission on the document root or a parent directory lacks execute bits needed to traverse paths. Fix ownership so the www-data group can read files, typically chown with www-data group membership and chmod 775 on directories. For Laravel, ensure root points at public/, not the project root. Connection refused externally is a different problem—usually UFW, cloud security groups, or port blocks rather than file permissions.

Ubuntu 24.04 LTS is the current long-term choice with support through 2029. Ubuntu 22.04 LTS remains viable until 2027. Both ship Nginx in default repositories and receive regular security updates. I deploy Nginx on both 22.04 and 24.04 VPS instances weekly for client projects. Choose 24.04 for new servers unless an existing workflow pins you to 22.04. Either way, run apt update before install and treat hardening as part of the setup checklist.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: