
How to Use NGINX to deploy a website on a VPS
Shamal Iroshan
2025-02-18 | 19 min read
Introduction to NGINX and VPS Deployment
A robust, open-source web server and reverse proxy, NGINX is renowned for its minimal resource use, great performance, and stability. It is frequently used as a reverse proxy to forward client requests to backend servers or to provide static material, such as HTML, CSS, and photos. Its capacity to effectively manage thousands of concurrent connections is one of its main advantages, which makes it a great option for websites with a lot of traffic.
A Virtual Private Server (VPS) is a virtual machine that runs its own copy of an operating system, offering dedicated resources such as CPU, RAM, and storage. A VPS gives users greater control and flexibility than shared hosting, enabling them to customise and tailor the server to meet their unique requirements. VPS hosting is a popular option for individuals and small organisations launching websites or applications since it is affordable and scalable.
Why Use NGINX for Deployment?
NGINX is highly versatile, and it's often used in various deployment scenarios, such as,
- Static Website Hosting: NGINX excels at serving static assets (HTML, CSS, JS) efficiently with minimal overhead.
- Reverse Proxy: It routes requests to backend servers, such as Node.js, Python, or PHP applications, and improves performance with caching and load balancing.
- Security: NGINX offers features like SSL termination and security enhancements (e.g., request rate limiting, DDoS mitigation).
- Performance: It handles concurrent connections efficiently, ensuring low latency even under heavy loads.
- Scalability: NGINX is optimized for large-scale deployments, making it ideal for growing websites or microservice architectures.
By combining a VPS with NGINX, users gain control over server configurations, optimised performance, and scalability, making it a preferred solution for deploying websites.
Prerequisites
Before we dive into deploying a website using NGINX on a VPS, ensure you have the following prerequisites set up.
-
VPS Setup: You will need a Virtual Private Server (VPS) where your website will be hosted. Common VPS providers include:
- DigitalOcean
- Amazon Web Services (AWS)
- Linode
- Vultr
These providers offer various plans, allowing you to choose a server that fits your performance and budget needs.
-
Basic Knowledge of Linux/Ubuntu: This guide assumes that you are familiar with basic Linux commands, as most VPS setups run on Linux distributions (Ubuntu is the most popular for web servers). You will need to navigate the terminal and use commands to manage your server.
-
SSH Access to the VPS: Secure Shell (SSH) is the most common way to access and manage your VPS remotely. You should have SSH credentials (IP address, username, password, or private key) to connect to your server. For example, you can use the following command to log in
ssh username@your-vps-ip-address
-
Domain Name (Optional but Recommended): If you plan to deploy a live website, it’s useful to have a domain name. Once you have a domain, you'll need to configure DNS settings to point to your VPS. This involves setting up an "A" record that directs traffic from your domain to your VPS’s public IP address. If you're using providers like DigitalOcean or AWS, they typically offer DNS management as part of their services.
-
Root or Sudo Privileges: To install NGINX and configure your server, you'll need either root access or a user with sudo privileges. This is necessary to perform administrative tasks, such as installing software, modifying configuration files, and restarting services.
Once these prerequisites are met, you're ready to begin setting up NGINX and deploying your website!
Install NGINX
Now that your VPS is set up, the next step is to install NGINX. Follow these steps to install and verify NGINX on a Linux-based VPS (assuming you're using Ubuntu or any Debian-based distribution).
1. Update Your Package List
Before installing any software, it’s always a good idea to update the package list to ensure you have the latest versions of all available packages. Run the following command
sudo apt update
2. Install NGINX
Once the package list is updated, you can install NGINX using the apt
package manager with the following command
sudo apt install nginx
This will install NGINX and any necessary dependencies on your VPS.
3. Verify NGINX Installation
After installation, it's important to verify that NGINX is running correctly. You can check its status by running
sudo systemctl status nginx
If NGINX is running, you should see an output that indicates it's active and running, something like
● nginx.service - A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since <time>
At this point, you can visit your VPS’s IP address in a browser, and you should see the default NGINX welcome page, confirming that NGINX is properly installed and running.
Managing NGINX with systemd
NGINX can be managed using systemd
, a service manager that helps you control services running on your Linux server. Here are a few basic commands to manage NGINX
- Start NGINX: If NGINX is not already running, you can start it using
sudo systemctl start nginx
- Stop NGINX: To stop NGINX, use the following command
sudo systemctl stop nginx
- Restart NGINX: To restart NGINX (useful when applying configuration changes), run
sudo systemctl restart nginx
- Reload NGINX: If you make changes to the NGINX configuration and want to apply them without stopping the service, use
sudo systemctl reload nginx
- Enable NGINX on Boot: To ensure that NGINX starts automatically when your VPS is rebooted, run
sudo systemctl enable nginx
With these commands, you can easily control the NGINX service and ensure it's always running as needed.
Set Up Directory and Permissions
Before serving your website with NGINX, you need to create the directory where your website files will reside and ensure that the proper permissions are set for both security and usability.
1. Create the Web Root Directory
The web root directory is where NGINX will look for the files to serve for your website. It's common to place these files in the /var/www/
directory. You can create a directory specifically for your website using the following commands
sudo mkdir -p /var/www/yourwebsite
mkdir -p /var/www/yourwebsite
: Creates the directory /var/www/yourwebsite
. The -p
option ensures that the parent directories are created if they don't already exist.
Next, change the ownership of the directory to your user so that you can easily manage the files within it
sudo chown -R $USER:$USER /var/www/yourwebsite
chown -R $USER:$USER /var/www/yourwebsite
: This command changes the ownership of the directory and all its subdirectories to your current user ($USER
), allowing you to read and write to it.
2. Add an Example index.html
File
Once the directory is created and the ownership is set, add a simple index.html
file to test if the website is working properly. You can create this file directly using the echo command
echo "<h1>Welcome to Your Website!</h1>" > /var/www/yourwebsite/index.html
This command creates a new index.html
file in the /var/www/yourwebsite
directory with a simple welcome message.
3. Set Appropriate Permissions
It's important to set the correct file and directory permissions to ensure that NGINX can read the files but others cannot modify them. The following command sets the permissions
sudo chmod -R 755 /var/www/yourwebsite
chmod -R 755 /var/www/yourwebsite
: This command sets the permissions recursively for the directory and all files within it. The permission755
means:- The owner (you) has read, write, and execute permissions.
- The group and others have read and execute permissions, but no write permissions, ensuring that others cannot modify your files.
With this setup, your NGINX server will be able to access and serve the content in /var/www/yourwebsite
while ensuring proper permissions and security.
Basic Configuration of NGINX
Once NGINX is installed and running, the next step is to configure it to serve your website. NGINX uses configuration files to control its behaviour, including how it handles requests, where to find the website files, and how to respond to different domain names.
1. Structure of NGINX Configuration Files
The main NGINX configuration file is located at /etc/nginx/nginx.conf
. This file defines global settings and includes other configuration files, such as those for individual server blocks (virtual hosts). The configuration is usually organised like this:
- /etc/nginx/nginx.conf: The main configuration file for global settings.
- /etc/nginx/sites-available/: Directory where individual site configurations are stored. These files define how NGINX should handle traffic for each site.
- /etc/nginx/sites-enabled/: Contains symbolic links to the files in
sites-available
, which are the actual active site configurations.
To configure a specific website, you will typically create a new configuration file in the sites-available
directory and then link it to sites-enabled
.
2. Adding a New Server Block (Virtual Host)
A server block is a configuration block that defines how NGINX will respond to requests for a specific domain or subdomain. Here's how you can add a new server block for your website
Create a New Server Block Configuration
Navigate to the sites-available
directory and create a new configuration file for your website
sudo nano /etc/nginx/sites-available/yourwebsite.com
In the file, add the following basic server block configuration
server {
listen 80;
server_name yourwebsite.com www.yourwebsite.com;
root /var/www/yourwebsite;
index index.html;
}
listen 80
: Tells NGINX to listen for HTTP requests on port 80.server_name
: Defines the domain names for which this server block will respond. Replaceyourwebsite.com
with your actual domain.root
: Specifies the directory where your website files (e.g., HTML, CSS, JS) are stored. Ensure this directory exists (e.g.,/var/www/yourwebsite
).index
: Specifies the default file to serve when a request is made to the root URL. In this case, it will look forindex.html
.
3. Link the Configuration
To activate the new server block, create a symbolic link from sites-available
to sites-enabled
sudo ln -s /etc/nginx/sites-available/yourwebsite.com /etc/nginx/sites-enabled/
This tells NGINX to use the new configuration when handling incoming requests.
4. Test and Reload NGINX
Before applying the changes, it's always a good idea to test the configuration for any syntax errors
sudo nginx -t
If the test passes successfully, you can reload NGINX to apply the new configuration
sudo systemctl reload nginx
At this point, if your domain is properly configured to point to your VPS (through DNS settings), visiting http://yourwebsite.com
should display the content from your index.html
file. Your NGINX server is now serving your website!
Configuring a Domain Name with NGINX
To make your website accessible via a domain name, you need to configure both your domain’s DNS settings and update the NGINX configuration to recognize the domain. Here’s how to do it step by step.
1. Pointing Your Domain Name to the VPS using DNS A Records
To connect your domain to your VPS, you need to create a DNS A record that points to your VPS’s IP address. The steps for configuring DNS vary depending on your domain registrar (e.g., GoDaddy, Namecheap, Google Domains), but the general process is similar.
Steps to Set Up the A Record:
-
Log in to your domain registrar’s control panel: Go to the DNS management or settings page for your domain.
-
Add an A Record: Create a new A record with the following details:
- Name/Host: This is usually
@
to signify the root domain (e.g.,yourwebsite.com
) orwww
if you want to configurewww.yourwebsite.com
. - Type: Choose
A
for an A record. - Value: Enter your VPS’s public IP address (the IP address where NGINX is running).
- TTL: You can leave this at the default value (typically 3600 seconds).
- Name/Host: This is usually
Example configuration:
- Host:
@
- Type:
A
- Value:
123.456.78.90
(your VPS IP) - TTL:
3600
Once this is set up, it can take a few minutes to a few hours for the DNS changes to propagate across the internet.
2. Update the server_name
in the NGINX Configuration
After setting up the DNS A record, you need to tell NGINX to respond to requests for your domain name. This is done by updating the server_name
directive in your NGINX server block.
Step 1: Edit Your NGINX Configuration File
Open the NGINX configuration file for your website located in /etc/nginx/sites-available
sudo nano /etc/nginx/sites-available/yourwebsite.com
Find the server_name
directive and update it to include your domain name. For example
server {
listen 80;
server_name yourwebsite.com www.yourwebsite.com;
root /var/www/yourwebsite;
index index.html;
}
server_name yourwebsite.com www.yourwebsite.com;
: Replace yourwebsite.com
with your actual domain name. This line ensures that NGINX will handle requests for both yourwebsite.com
and www.yourwebsite.com
.
Step 2: Test and Reload NGINX
After making changes to the configuration file, it’s important to test the configuration to ensure there are no syntax errors
sudo nginx -t
If the test passes successfully, reload NGINX to apply the changes
sudo systemctl reload nginx
3. Verify the Domain Configuration
After DNS propagation, you can verify that your domain is correctly configured by visiting your domain in a browser (e.g., http://yourwebsite.com
). If everything is set up correctly, you should see your website being served by NGINX.
At this point, your domain is configured with NGINX and pointing to your VPS, making your website accessible via your domain name.
Setting Up SSL with Let’s Encrypt (Optional but Recommended)
Securing your website with HTTPS is a critical step in protecting your users' data and ensuring trust. HTTPS encrypts data between the user's browser and your server, preventing unauthorized access or tampering. Additionally, many browsers flag HTTP-only sites as "Not Secure," and search engines like Google prioritize HTTPS websites in search results.
To secure your website, you can use Let’s Encrypt, a free, automated, and open Certificate Authority (CA) that provides SSL certificates. Let’s Encrypt also offers a tool called Certbot, which helps in automatically issuing and renewing these certificates.
1. Importance of Securing Your Website with HTTPS
- Encryption: Protects sensitive information exchanged between users and your server (e.g., passwords, personal data).
- Trust and Credibility: Modern browsers display a padlock icon for HTTPS-enabled sites, signaling security to your visitors.
- SEO Benefits: HTTPS is a ranking signal, so it can improve your site’s visibility in search engine results.
- Avoiding Warnings: Without HTTPS, most browsers display warnings to users, which can drive visitors away from your site.
2. How to Install Certbot and Obtain an SSL Certificate
To install Certbot and configure SSL for your domain, follow these steps:
Step 1: Install Certbot and the NGINX Plugin
Certbot is a utility that helps automate the process of obtaining and renewing SSL certificates from Let’s Encrypt. The NGINX plugin ensures that Certbot can update your NGINX configuration to enable HTTPS.
Run the following commands to install Certbot and its NGINX plugin
sudo apt install certbot python3-certbot-nginx
Step 2: Obtain an SSL Certificate
Once Certbot is installed, you can request an SSL certificate for your domain. Certbot will automatically configure your NGINX server to use the certificate and set up HTTPS.
Run the following command, replacing yourwebsite.com
and www.yourwebsite.com
with your actual domain names
sudo certbot --nginx -d yourwebsite.com -d www.yourwebsite.com
This command will:
- Request an SSL certificate for both
yourwebsite.com
andwww.yourwebsite.com
. - Automatically update your NGINX configuration to use the newly issued certificate.
- Enable HTTPS for your site.
Follow the on-screen instructions to complete the setup.
Step 3: Verify HTTPS
After the process is complete, you can verify that your website is secured by visiting https://yourwebsite.com
. You should see the padlock icon in the browser, indicating that the connection is secured by SSL.
3. How to Auto-Renew SSL Certificates
Let’s Encrypt certificates are valid for 90 days, but Certbot can automatically renew them to avoid any downtime.
Step 1: Verify Automatic Renewal
Certbot installs a cron job to automatically check and renew your SSL certificates before they expire. You can manually verify the renewal process by running this command
sudo certbot renew --dry-run
This will simulate a certificate renewal and ensure that everything is working correctly. If no errors appear, Certbot will automatically renew your certificates and reload NGINX when needed.
Step 2: Check the Renewal Logs
You can check the status of your certificate renewals in the Certbot logs located at /var/log/letsencrypt/letsencrypt.log
to ensure everything is functioning properly.
Managing Firewall (if needed)
If your VPS has a firewall enabled, it’s essential to ensure that traffic can reach your website by allowing the necessary ports for HTTP (port 80) and HTTPS (port 443). If you're using a firewall on your server, such as UFW (Uncomplicated Firewall), you’ll need to configure it to allow traffic on these ports.
1. Opening Ports for HTTP and HTTPS
When deploying a website with NGINX, you need to open two specific ports to allow traffic to your website:
- Port 80: Used for HTTP (non-secure traffic).
- Port 443: Used for HTTPS (secure, SSL-encrypted traffic).
If you're using a firewall, like UFW, you can allow these ports by running the following commands.
2. Example Using UFW (Uncomplicated Firewall)
Step 1: Allow HTTP and HTTPS Traffic
UFW provides a simple way to configure firewall rules for NGINX. The Nginx Full
application profile allows both HTTP and HTTPS traffic through ports 80 and 443. You can allow these with the following command
sudo ufw allow 'Nginx Full'
This command will
- Open port 80 for HTTP traffic.
- Open port 443 for HTTPS traffic.
Step 2: Enable the Firewall
If UFW is not already enabled, you can enable it with the following command
sudo ufw enable
Once enabled, UFW will start blocking any other unauthorized traffic, only allowing HTTP and HTTPS traffic to your server.
Step 3: Verify the Firewall Rules
After configuring the firewall, it’s always a good idea to check which ports are open. You can verify the firewall rules with
sudo ufw status
This will output the currently active firewall rules, showing that Nginx Full is allowed
Status: active
To Action From
-- ------ ----
Nginx Full ALLOW Anywhere
Nginx Full (v6) ALLOW Anywhere (v6)
By enabling the firewall with these rules, you ensure that only web traffic (on ports 80 and 443) is allowed through, improving the security of your VPS.
Testing the Website
Once NGINX is installed and configured, and your firewall is set up, the final step is to test your website to ensure it’s accessible and running smoothly. This section will walk you through the process of checking your website in a browser and troubleshooting common issues that may arise.
1. Check the Website in the Browser
After completing the NGINX configuration, domain setup, and firewall management, open a browser and visit your domain or VPS IP address:
- If using a domain name: Visit
http://yourwebsite.com
orhttps://yourwebsite.com
if you’ve set up SSL. - If using the VPS IP address: Visit
http://<your-vps-ip>
in your browser.
You should see the content of your website (e.g., the "Welcome to Your Website!" message if you used the example HTML file).
2. Troubleshooting Common Issues
If your website is not accessible, here are a few things to check:
-
Check DNS Propagation: If you’ve just updated your domain’s DNS records, it may take a few hours for the changes to propagate. Use tools like DNS Checker to confirm if your domain is pointing to the correct IP address.
-
Check Firewall Configuration: Ensure that ports 80 and 443 are open in your firewall by running
sudo ufw status
. If they are not allowed, usesudo ufw allow 'Nginx Full'
to allow HTTP/HTTPS traffic. -
Verify NGINX Configuration: If NGINX is not responding, ensure that there are no syntax errors in your configuration. You can test the NGINX configuration file using
sudo nginx -t
- If there are any issues, this command will show an error message indicating what needs to be fixed.
3. Check NGINX Logs for Errors
If the website still isn’t working after checking the configuration and DNS, you can review the NGINX error logs for more detailed information. The error log is located at /var/log/nginx/error.log
. To view the logs in real-time, use the following command
sudo tail -f /var/log/nginx/error.log
Look for any specific error messages that could indicate what went wrong. Common issues might include:
- Permission issues with the web root directory.
- Misconfigured server blocks in the NGINX configuration.
- Firewall issues blocking access to the server.
Use the logs to troubleshoot and resolve any errors.
Conclusion
In this guide, we covered the essential steps for deploying a website on a VPS using NGINX. From installing NGINX, configuring server blocks, and setting up SSL with Let’s Encrypt, to managing firewall rules and testing your deployment, you now have the foundational knowledge to host your own website efficiently.
NGINX's flexibility makes it a powerful choice for a variety of deployment scenarios, whether you're hosting a simple static website or more complex applications. Its ability to act as a web server, reverse proxy, and load balancer, combined with its performance and scalability, makes it a popular option for developers and businesses alike.
As you become more familiar with NGINX, you can explore advanced topics such as:
- Reverse proxy setups to manage traffic to backend applications.
- Load balancing to distribute traffic across multiple servers for higher availability.
- Performance tuning to optimise server resources and handle high traffic efficiently.
By diving into these advanced configurations, you can unlock the full potential of NGINX and tailor it to your specific needs. Happy deploying!
Further Reading
For more detailed configurations and advanced topics, check out the official documentation