Net2Secure: A Leading Data Center Service Provider in India
Grab the Freedom Deal: ₹2,000 FREE Cloud Credits! Claim Now
Grab the Freedom Deal: ₹2,000 FREE Cloud Credits! Claim Now
Grab the Freedom Deal: ₹2,000 FREE Cloud Credits! Claim Now
Grab the Freedom Deal: ₹1,000 FREE Cloud Credits! Claim Now
+91 9953046498 sales@net2secure.com Support Login | Register

⮚ KB ⮚ How to Set Up Nginx on Linux VPS: Ubuntu &...

How to Set Up Nginx on Linux VPS: Ubuntu & Debian Guide


Nginx is a widely used web server and reverse proxy for serving websites, APIs, static files and application traffic. This guide explains how to install and configure Nginx on an Ubuntu or Debian Linux VPS, connect a domain, create a server block, proxy a Node.js application, enable HTTPS with Let's Encrypt, secure the basic setup and troubleshoot common errors.

Quick answer:

On a current Ubuntu or Debian VPS, update the package index, install Nginx with APT, verify the service, allow SSH and web traffic through the firewall, create a domain-specific server block, point your DNS records to the VPS, test the configuration with sudo nginx -t, and reload Nginx. For a public production site, add HTTPS after DNS is resolving correctly.

What Is Nginx and Why Use It on a Linux VPS?

Nginx is an HTTP server that can also operate as a reverse proxy. On a Linux VPS, it can serve static websites directly or receive public HTTP and HTTPS requests before forwarding application traffic to software such as a Node.js service listening on a private local port.

A VPS gives administrators control over the operating system and web-server configuration. If you need that level of control for websites or applications. For projects specifically using Ubuntu, see  Ubuntu VPS Hosting in India .

Use Case How Nginx Is Used
Static website Serves HTML, CSS, JavaScript, images and downloads directly.
Node.js application Acts as a reverse proxy to an application bound to localhost.
API Accepts public HTTP/HTTPS requests and forwards them upstream.
Multiple domains Uses separate server blocks selected by the requested hostname.
HTTPS termination Handles TLS certificates while the application can remain on a local port.

What You Need Before Setting Up Nginx

For the Ubuntu/Debian procedure in this guide, prepare:

  • An Ubuntu or Debian VPS with sudo-capable administrative access.
  • SSH access to the server.
  • A public IPv4 address and, if you intend to use IPv6, a correctly routed IPv6 address.
  • A domain name if you want hostname-based hosting and HTTPS.
  • Access to the domain's DNS records.

Distribution note: The commands below target Ubuntu and Debian systems that use APT and systemd. RHEL, Rocky Linux, AlmaLinux, Fedora, Arch Linux and other distributions use different package and firewall tooling. Do not copy APT or UFW instructions blindly onto a different distribution.

If you want a VPS environment before deploying Nginx, compare Net2Secure VPS Hosting in India. You can also review the current Linux VPS free-trial information or VPS server trial terms before requesting an evaluation. Trial eligibility, resources and other conditions should be confirmed before deployment.

How to Install Nginx on Ubuntu or Debian VPS

Update the package index

sudo apt update

Install Nginx

sudo apt install nginx

The Ubuntu package installation normally starts Nginx automatically. Verify the service rather than assuming it started successfully.

Check the Nginx service

sudo systemctl status nginx

Look for active (running). Press q to leave the status viewer.

Start Nginx if required

sudo systemctl start nginx

Enable Nginx at boot

sudo systemctl enable nginx

You can confirm whether it is enabled with:

systemctl is-enabled nginx

Check the installed Nginx version

nginx -v

You can now test the web server using the VPS IP address in a browser:

http://YOUR_SERVER_IP

If you see the default Nginx page, the web server is responding on port 80.

Configure UFW Without Locking Yourself Out of SSH

On Ubuntu, UFW provides a simpler interface for host firewall rules. A remote VPS administrator should permit the actual SSH service or SSH port before enabling the firewall.

Important: If your SSH daemon uses a custom port rather than port 22, allow that real port before enabling UFW. Enabling a firewall without an SSH rule can disconnect your remote session and prevent reconnection.

Allow SSH first

If SSH uses the standard service profile:

sudo ufw allow OpenSSH

Or explicitly allow port 22 if that is the port your SSH daemon uses:

sudo ufw allow 22/tcp

Check available application profiles

sudo ufw app list

If Nginx application profiles are present, you can allow both HTTP and HTTPS with:

sudo ufw allow 'Nginx Full'

Alternatively, permit the ports explicitly:

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

Enable and inspect UFW

sudo ufw enable
sudo ufw status verbose

Debian installations do not necessarily have UFW installed or selected as the firewall interface. Check the server's existing firewall strategy before adding another firewall manager.

Create an Nginx Server Block for Your Domain

Debian and Ubuntu package configurations commonly use /etc/nginx/sites-available/ for site configuration and symbolic links in /etc/nginx/sites-enabled/ for enabled sites.

The example below uses example.com. Replace it everywhere with your actual domain.

Create the document root

sudo mkdir -p /var/www/example.com/html
sudo chown -R "$USER":"$USER" /var/www/example.com
sudo chmod -R 755 /var/www/example.com

Create a test page

cat > /var/www/example.com/html/index.html <<'EOF'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Nginx is working</title>
</head>
<body>
  <h1>Nginx is working on this Linux VPS.</h1>
</body>
</html>
EOF

Create the server-block configuration

sudo nano /etc/nginx/sites-available/example.com

Add:

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;
    }
}

Save the file, then enable the site with a symbolic link:

sudo ln -s /etc/nginx/sites-available/example.com \
/etc/nginx/sites-enabled/example.com

Do not remove the default site until the new configuration has passed a syntax test and you have confirmed that your intended site works.

Point the Domain to Your Linux VPS

At your DNS provider, create an A record that points the hostname to your VPS's public IPv4 address.

Record Name Value When to Use It
A @ YOUR_IPV4_ADDRESS Maps the root domain to the VPS IPv4 address.
A www YOUR_IPV4_ADDRESS Maps www.example.com to the same IPv4 address.
AAAA @ YOUR_IPV6_ADDRESS Use only when IPv6 is correctly configured and reachable.
AAAA www YOUR_IPV6_ADDRESS Optional IPv6 record for the www hostname.

Do not add a placeholder AAAA record. If your domain advertises IPv6 but the VPS or web server is not reachable over that IPv6 address, users and certificate validation can fail. Configure IPv6 correctly or omit the AAAA record.

Check DNS from the command line

dig +short A example.com
dig +short AAAA example.com

DNS changes can be cached according to the records' TTL and resolver behavior, so confirm that the public records return the intended VPS addresses before requesting a TLS certificate.

Test the Nginx Configuration Before Reloading

Always test the configuration after editing Nginx files:

sudo nginx -t

A successful test should report that the syntax is OK and the test succeeds.

Then reload Nginx gracefully:

sudo systemctl reload nginx

A reload is normally preferable to an unnecessary restart after a valid configuration change because Nginx can apply the new configuration while existing workers finish current requests.

Optional: disable the default site

After your own server block has been tested and is working, you can remove the default enabled-site link if you no longer need it:

sudo rm /etc/nginx/sites-enabled/default
sudo nginx -t
sudo systemctl reload nginx

How to Use Nginx as a Reverse Proxy for Node.js

Direct answer: Run the Node.js application on a private local address such as 127.0.0.1:3000, then configure Nginx to listen publicly on ports 80/443 and forward requests to that local application. This avoids exposing the application port directly to the internet.

Verify that Node.js is listening locally

curl http://127.0.0.1:3000

If this fails, fix the application before troubleshooting Nginx. A reverse proxy cannot successfully reach an upstream service that is stopped or listening on a different port.

Basic Node.js reverse-proxy server block

server {
    listen 80;
    listen [::]:80;

    server_name example.com www.example.com;

    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;
    }
}

Test and reload after saving:

sudo nginx -t
sudo systemctl reload nginx

WebSocket support

WebSocket proxying needs explicit handling of the HTTP Upgrade and Connection headers because these hop-by-hop headers are not automatically forwarded to the upstream server.

On the standard Ubuntu/Debian Nginx package layout, create a map inside Nginx's http context. One convenient location is:

sudo nano /etc/nginx/conf.d/websocket-map.conf

Add:

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

Then use these directives in the proxied location:

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;

    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
}

Again, validate before applying:

sudo nginx -t
sudo systemctl reload nginx

Keep the Node.js application bound to localhost unless it genuinely needs direct external access. If Nginx is the public entry point, there is usually no reason to open port 3000 in UFW.

Enable HTTPS on Nginx with Certbot and Let's Encrypt

Do this only after the domain resolves to the VPS and ports 80/443 are permitted by the relevant network and host firewalls.

Install Certbot using the currently recommended Snap method

sudo snap install --classic certbot

Create or refresh a command link:

sudo ln -sf /snap/bin/certbot /usr/local/bin/certbot

Request and install the certificate with the Nginx plugin

sudo certbot --nginx -d example.com -d www.example.com

Certbot can locate the matching Nginx server block, obtain the certificate after successful domain validation and update the server configuration. Review the changes rather than treating automated configuration as a substitute for configuration management.

Verify the Nginx configuration after Certbot

sudo nginx -t
sudo systemctl status nginx

Test automatic certificate renewal

sudo certbot renew --dry-run

You can also inspect the Certbot renewal timer on a Snap installation:

sudo systemctl status snap.certbot.renew.timer

Let's Encrypt HTTP-01 validation uses port 80. If validation fails, verify public DNS, firewall rules, HTTP reachability and any AAAA record before repeatedly retrying certificate issuance.

Basic Nginx Security and Performance Practices

Installing Nginx is only the first step. A production VPS also needs routine operating-system and application maintenance.

Keep Ubuntu/Debian packages updated

sudo apt update
sudo apt upgrade

Expose only required ports

A typical public Nginx server needs SSH administration plus HTTP and HTTPS. Application ports such as a Node.js service on port 3000 should normally remain private when Nginx proxies to them locally.

Reduce unnecessary version disclosure

Inside the appropriate Nginx http, server or location context you can use:

server_tokens off;

This reduces version information in some Nginx-generated responses. It is not a substitute for security updates, firewalling or secure application code.

Add headers intentionally, not blindly

Some sites can use headers such as:

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

Framing policy, Content Security Policy and HSTS should be designed around the actual application. In particular, enable HSTS only after HTTPS is stable and you understand its effect on future browser connections.

Be selective with compression

Nginx supports gzip response compression, which may reduce transferred response size, but compression over TLS can introduce security considerations for responses containing secrets. Do not enable an aggressive copy-and-paste gzip configuration without considering the content being compressed.

Back up before significant changes

Keep restorable copies of website content, application data and important configuration. Before automated tools modify an Nginx setup, a configuration backup also gives you a simpler recovery path.

How to Check Nginx Access and Error Logs

On standard Debian/Ubuntu package installations, the main logs are commonly:

/var/log/nginx/access.log
/var/log/nginx/error.log

Follow the error log in real time

sudo tail -f /var/log/nginx/error.log

Follow requests in the access log

sudo tail -f /var/log/nginx/access.log

Inspect recent Nginx service messages

sudo journalctl -u nginx --since "30 minutes ago"

Logs often reveal whether a problem comes from filesystem permissions, a missing file, an upstream connection failure, a malformed configuration or a different server block receiving the request.

Common Nginx Problems on a Linux VPS

Problem Likely Causes What to Check
403 Forbidden Filesystem permissions, missing readable index, restrictive directory access. Document root, file ownership/mode and error log.
404 Not Found Wrong root path, wrong server block, missing file or try_files result. server_name, root, requested path and active configuration.
502 Bad Gateway Upstream application stopped, wrong port/socket or failed local connection. Node.js process, localhost port and Nginx error log.
Nginx will not start Syntax error, duplicate/conflicting listen settings or port already occupied. nginx -t, journalctl and listening processes.
Wrong website appears DNS mismatch or another server block matched the hostname. DNS A/AAAA, server_name and enabled sites.
Certbot validation fails Incorrect DNS, blocked port 80, bad IPv6 record or wrong server block. Public A/AAAA resolution and HTTP reachability.

Fix a 403 Forbidden response

Check the error log first:

sudo tail -n 50 /var/log/nginx/error.log

Verify the directory and file permissions:

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

Nginx must be able to traverse the parent directories and read the file it is serving. Avoid solving permissions problems with unsafe broad write permissions such as chmod -R 777.

Fix an unexpected 404

sudo nginx -T | less

Inspect the effective server_name, root, location and try_files settings and confirm that the requested file exists under the configured document root.

Fix a 502 Bad Gateway with Node.js

Test the upstream directly:

curl -v http://127.0.0.1:3000

Check whether a process is listening:

sudo ss -ltnp | grep ':3000'

If nothing is listening, start or troubleshoot the Node.js application. If it listens on another address or port, correct the Nginx proxy_pass target.

Find a port 80 conflict

sudo ss -ltnp | grep ':80 '

If Apache is already installed, inspect it:

sudo systemctl status apache2

Stop or disable another web server only when you have intentionally chosen Nginx to replace it and understand what workloads depend on the other service.

Check Nginx configuration errors

sudo nginx -t
sudo journalctl -u nginx -n 100 --no-pager

Nginx on Ubuntu VPS vs Other Linux Distributions

Distribution Family Typical Package Tool This Guide's Commands?
Ubuntu APT Yes
Debian APT Mostly yes; verify firewall tooling and package differences.
RHEL / Rocky / AlmaLinux / Fedora DNF No. Use distribution-specific package, SELinux and firewall guidance.
Arch Linux pacman No. Use Arch-specific documentation and paths.

This distinction matters because package versions, default configuration paths, firewall systems, mandatory-access-control systems and service defaults can vary by distribution.

Need a Linux VPS for Nginx Hosting?

Nginx needs an environment where you can install packages, edit server configuration and manage application services. Compare Net2Secure's Ubuntu and Linux VPS Hosting options according to the CPU, RAM, storage, bandwidth, operating-system and management requirements of your workload.

Not ready to choose a paid configuration? Review the currently published trial information and confirm eligibility, available resources, access, server location and other conditions with Net2Secure before deploying a production workload.

Frequently Asked Questions About Nginx on Linux VPS

How do I install Nginx on an Ubuntu VPS?

Update the package index with sudo apt update, install Nginx with sudo apt install nginx, and verify the service with sudo systemctl status nginx. Configure the firewall before exposing the server publicly.

How do I know whether Nginx is running?

Run sudo systemctl status nginx. You can also request the server locally with curl http://127.0.0.1 or test its public IP from a browser when firewall rules permit HTTP.

Where are Nginx server blocks stored on Ubuntu and Debian?

The distribution package commonly stores site configurations in /etc/nginx/sites-available/ and enables them using symbolic links in /etc/nginx/sites-enabled/.

How do I test an Nginx configuration before applying it?

Run sudo nginx -t. If the test succeeds, apply the change with sudo systemctl reload nginx. Do not reload a known-bad configuration.

Can I use Nginx to host a Node.js application?

Yes. A common architecture runs Node.js on a local port such as 127.0.0.1:3000 while Nginx accepts public traffic on ports 80 and 443 and forwards requests using proxy_pass.

Does Nginx support WebSockets with Node.js?

Yes, but WebSocket proxying requires appropriate handling of the Upgrade and Connection headers. Test both normal HTTP requests and the application's WebSocket connection after changing the proxy configuration.

How do I enable HTTPS on Nginx?

Once the domain resolves to the VPS and HTTP is publicly reachable, Certbot's Nginx plugin can request a Let's Encrypt certificate and configure Nginx. Test renewal afterwards with sudo certbot renew --dry-run.

Why does Certbot need port 80?

The commonly used Let's Encrypt HTTP-01 challenge validates domain control through HTTP on port 80. DNS and firewall configuration must therefore allow the validation request to reach the correct server.

Why am I getting a 502 Bad Gateway from Nginx?

A 502 response commonly indicates that Nginx cannot successfully communicate with its configured upstream service. Check that the Node.js or other backend process is running and that proxy_pass points to the correct address and port.

Why does Nginx show 403 Forbidden?

Check the Nginx error log, document-root permissions and index file. Nginx needs permission to traverse the relevant directories and read the content being served.

Is Ubuntu VPS suitable for Nginx hosting?

Ubuntu provides packaged Nginx, systemd service management and extensive server documentation, making it a practical choice for administrators who want to run Nginx on a VPS. The right VPS size depends on the website or application's CPU, memory, storage and traffic requirements.

Can I try a Net2Secure VPS before deploying Nginx?

Net2Secure publishes Linux VPS trial information and a separate VPS server trial page. Check the current eligibility, duration, resource allocation, operating system, permissions, location and other conditions before activation.

Experience VPS Hosting Before You Buy

Choose your preferred VPS trial and test the right server environment for your requirements.

☁

VPS Server Trial

Test cloud VPS performance, server resources and application compatibility.

Start VPS Trial →
🐧

Linux VPS Hosting Trial

Explore Linux VPS for websites, development and application hosting.

Try Linux VPS →
💻

Windows VPS Trial

Test Windows VPS for remote desktop access and business applications.

Try Windows VPS →

Trial eligibility, availability and applicable terms may vary.


Abhay Pratap Singh

By Abhay Pratap Singh

Abhay Singh is a digital marketing strategist, technology writer, and SEO specialist with a passion for helping businesses grow through data-driven digital solutions. He specializes in search engine optimization (SEO), web hosting technologies, cybersecurity trends, cloud computing, website performance optimization, and emerging digital innovations.

With years of experience in content strategy and technical SEO, Abhay has authored numerous in-depth guides, tutorials, and industry insights that help businesses, website owners, and IT professionals navigate the evolving digital landscape. His expertise spans website optimization, DNS management, web hosting infrastructure, cybersecurity best practices, and AI-driven digital marketing strategies.

View all of Abhay Pratap Singh's posts.

Contact Us

Latest Articles

We use cookies

By continuing to browse this site, you are agreeing to the use of cookies to enhance your experience.

EXCLUSIVE CLOUD OFFER • GET ₹2,000 FREE CLOUD CREDITS!

Claim ₹2,000 Credits

Signup with Net2Secure and make your first recharge of ₹2,000 to get additional ₹2,000 add-on credits.

Only for New Customers • Terms Apply

Get ₹2,000
Free Cloud Credits!

Supercharge your workloads with Net2Secure enterprise cloud infrastructure. High speed, zero upfront commitment!

₹2,000 FREE CLOUD CREDITS
✦
✦
  • Get ₹2,000 Wallet Bonus on first recharge
  • High-Speed Cloud Server Deployment
  • 24/7 Dedicated Server Support & 99.95% Uptime