Table of Contents
URL: https://www.progressiverobot.com/how-to-install-nginx-on-ubuntu-22-04/
Introduction
Nginx is one of the most popular web servers in the world, powering over 33% of all websites globally. It's responsible for hosting some of the largest and highest-traffic sites on the internet, including Netflix, Pinterest, and Airbnb. Nginx is a lightweight, high-performance choice that excels as both a web server and reverse proxy.
This comprehensive guide covers installing and configuring Nginx on Ubuntu 22.04, 24.04, and 25.04, with step-by-step instructions for firewall configuration, security hardening, performance optimization, and troubleshooting common issues.
Key Takeaways
- Installation & Setup: Learn how to install Nginx from Ubuntu's official repositories, configure firewall rules with UFW, and verify the installation
- Service Management: Master systemd commands to start, stop, enable, and reload Nginx, plus verify service status and configuration
- Server Configuration: Configure server blocks (virtual hosts) to host multiple domains, set up document roots, and manage Nginx directives
- Security Hardening: Implement security best practices including SSL/TLS with Let's Encrypt, security headers, rate limiting, and access controls
- Performance Optimization: Fine-tune worker processes, connection limits, caching, and compression for optimal performance
- Reverse Proxy & Load Balancing: Set up Nginx as a reverse proxy for backend applications with load balancing capabilities
- Troubleshooting & Logs: Monitor access and error logs, diagnose common issues, and implement effective debugging strategies
- Version-Specific Features: Understand key differences between Ubuntu 22.04, 24.04, and 25.04 for Nginx deployments
- Maintenance & Monitoring: Establish backup routines, implement monitoring, and maintain server health with regular updates
- Production Readiness: Deploy a secure, optimized, and well-configured Nginx server suitable for production environments
[info] Deploy your applications from GitHub using an app platform. Let the cloud provider focus on scaling your app.
Prerequisites
Before you begin this guide, you should have:
- Ubuntu Server: Ubuntu 22.04 LTS, 24.04 LTS, or 25.04 setup and installed.
- Non-root user: A regular user account with sudo privileges configured.
- Domain name (optional): For server block configuration and SSL setup
- Basic terminal knowledge: Familiarity with command-line operations.
| Ubuntu Version | Nginx Version | Support Status | Notes |
|---|---|---|---|
| Ubuntu 22.04 LTS | 1.18.0+ | Fully Supported | Long-term support until 2027 |
| Ubuntu 24.04 LTS | 1.24.0+ | Fully Supported | Latest LTS with enhanced security |
| Ubuntu 25.04 | 1.26.0+ | Fully Supported | Latest features and performance improvements |
You can learn how to configure a regular user account by following our Initial server setup guide for Ubuntu.
To learn more about setting up a domain name with the cloud provider, please refer to our Introduction to DNS hosting.
When you have an account available, log in as your non-root user to begin.
Step 1 – Installing Nginx
Nginx is available in Ubuntu's default repositories for all supported versions. We'll install it using the apt packaging system with the latest stable version.
Update System Packages
First, update your local package index to ensure you have access to the most recent package listings:
sudo apt update
sudo apt upgrade -y
Install Nginx
Install Nginx using the following command:
sudo apt install nginx -y
Press Y when prompted to confirm installation. If you are prompted to restart any services, press ENTER to accept the defaults and continue. apt will install Nginx and any required dependencies to your server.
Verify Installation
Check the installed Nginx version:
nginx -v
Expected output:
nginx version: nginx/1.24.0 (Ubuntu)
Check Installation Status
Verify that Nginx was installed correctly:
dpkg -l | grep nginx
You should see output similar to:
ii nginx-common 1.24.0-1ubuntu1 all small, powerful, scalable web/proxy server - common files
ii nginx-core 1.24.0-1ubuntu1 amd64 nginx web/proxy server (core version)
ii nginx 1.24.0-1ubuntu1 all small, powerful, scalable web/proxy server (default version)
Step 2 – Adjusting the Firewall
Before testing Nginx, the firewall software needs to be configured to allow access to the service. Nginx registers itself as a service with ufw upon installation, making it straightforward to allow Nginx access.
List the application configurations that ufw knows how to work with by typing:
sudo ufw app list
You should get a listing of the application profiles:
[secondary_label Output]
Available applications:
Nginx Full
Nginx HTTP
Nginx HTTPS
OpenSSH
As demonstrated by the output, there are three profiles available for Nginx:
- Nginx Full: This profile opens both port 80 (normal, unencrypted web traffic) and port 443 (TLS/SSL encrypted traffic)
- Nginx HTTP: This profile opens only port 80 (normal, unencrypted web traffic)
- Nginx HTTPS: This profile opens only port 443 (TLS/SSL encrypted traffic)
It is recommended that you enable the most restrictive profile that will still allow the traffic you've configured. Right now, we will only need to allow traffic on port 80.
You can enable this by typing:
sudo ufw allow 'Nginx HTTP'
You can verify the change by typing:
sudo ufw status
The output will indicated which HTTP traffic is allowed:
[secondary_label Output]
Status: active
To Action From
-- ------ ----
OpenSSH ALLOW Anywhere
Nginx HTTP ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
Nginx HTTP (v6) ALLOW Anywhere (v6)
Step 3 – Checking your Web Server
At the end of the installation process, Ubuntu 22.04 starts Nginx. The web server should already be up and running.
We can check with the systemd init system to make sure the service is running by typing:
systemctl status nginx
[secondary_label Output]
● 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 Fri 2022-03-01 16:08:19 UTC; 3 days ago
Docs: man:nginx(8)
Main PID: 2369 (nginx)
Tasks: 2 (limit: 1153)
Memory: 3.5M
CGroup: /system.slice/nginx.service
├─2369 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
└─2380 nginx: worker process
As confirmed by this out, the service has started successfully. However, the best way to test this is to actually request a page from Nginx.
You can access the default Nginx landing page to confirm that the software is running properly by navigating to your server's IP address. If you do not know your server's IP address, you can find it by using the icanhazip.com tool, which will give you your public IP address as received from another location on the internet:
curl -4 icanhazip.com
When you have your server's IP address, enter it into your browser's address bar:
http://<^>your_server_ip<^>
You should receive the default Nginx landing page:
If you are on this page, your server is running correctly and is ready to be managed.
Step 4 – Managing the Nginx Process
Now that you have your web server up and running, let's review some basic management commands.
To stop your web server, type:
sudo systemctl stop nginx
To start the web server when it is stopped, type:
sudo systemctl start nginx
To stop and then start the service again, type:
sudo systemctl restart nginx
If you are only making configuration changes, Nginx can often reload without dropping connections. To do this, type:
sudo systemctl reload nginx
By default, Nginx is configured to start automatically when the server boots. If this is not what you want, you can disable this behavior by typing:
sudo systemctl disable nginx
To re-enable the service to start up at boot, you can type:
sudo systemctl enable nginx
You have now learned basic management commands and should be ready to configure the site to host more than one domain.
Step 5 – Setting Up Server Blocks (Recommended)
When using the Nginx web server, _server blocks_ (similar to virtual hosts in Apache) can be used to encapsulate configuration details and host more than one domain from a single server. We will set up a domain called your_domain, but you should replace this with your own domain name.
Nginx on Ubuntu 22.04 has one server block enabled by default that is configured to serve documents out of a directory at /var/www/html. While this works well for a single site, it can become unwieldy if you are hosting multiple sites. Instead of modifying /var/www/html, let's create a directory structure within /var/www for our your_domain site, leaving /var/www/html in place as the default directory to be served if a client request doesn't match any other sites.
Create the directory for your_domain as follows, using the -p flag to create any necessary parent directories:
sudo mkdir -p /var/www/<^>your_domain<^>/html
Next, assign ownership of the directory with the $USER environment variable:
sudo chown -R $USER:$USER /var/www/<^>your_domain<^>/html
The permissions of your web roots should be correct if you haven't modified your umask value, which sets default file permissions. To ensure that your permissions are correct and allow the owner to read, write, and execute the files while granting only read and execute permissions to groups and others, you can input the following command:
sudo chmod -R 755 /var/www/<^>your_domain<^>
Next, create a sample index.html page using nano or your favorite editor:
nano /var/www/<^>your_domain<^>/html/index.html
Inside, add the following sample HTML:
[label /var/www/your_domain/html/index.html]
<html>
<head>
<title>Welcome to <^>your_domain<^>!</title>
</head>
<body>
<h1>Success! The <^>your_domain<^> server block is working!</h1>
</body>
</html>
Save and close the file by pressing Ctrl+X to exit, then when prompted to save, Y and then Enter.
In order for Nginx to serve this content, it's necessary to create a server block with the correct directives. Instead of modifying the default configuration file directly, let’s make a new one at /etc/nginx/sites-available/<^>your_domain<^>:
sudo nano /etc/nginx/sites-available/<^>your_domain<^>
Paste in the following configuration block, which is similar to the default, but updated for our new directory and domain name:
[label /etc/nginx/sites-available/your_domain]
server {
listen 80;
listen [::]:80;
root /var/www/<^>your_domain<^>/html;
index index.html index.htm index.nginx-debian.html;
server_name <^>your_domain<^> www.<^>your_domain<^>;
location / {
try_files $uri $uri/ =404;
}
}
Notice that we’ve updated the root configuration to our new directory, and the server_name to our domain name.
Next, let's enable the file by creating a link from it to the sites-enabled directory, which Nginx reads from during startup:
sudo ln -s /etc/nginx/sites-available/<^>your_domain<^> /etc/nginx/sites-enabled/
Note: Nginx uses a common practice called symbolic links, or symlinks, to track which of your server blocks are enabled. Creating a symlink is like creating a shortcut on disk, so that you could later delete the shortcut from the sites-enabled directory while keeping the server block in sites-available if you wanted to enable it.
Two server blocks are now enabled and configured to respond to requests based on their listen and server_name directives (you can learn more about how Nginx processes these directives in our detailed guide).
your_domain: Will respond to requests foryour_domainandwww.your_domain.default: Will respond to any requests on port 80 that do not match the other two blocks.
To avoid a possible hash bucket memory problem that can arise from adding additional server names, it is necessary to adjust a single value in the /etc/nginx/nginx.conf file. Open the file:
sudo nano /etc/nginx/nginx.conf
Find the server_names_hash_bucket_size directive and remove the # symbol to uncomment the line. If you are using nano, you can quickly search for words in the file by pressing CTRL and w.
Note: Commenting out lines of code — usually by putting # at the start of a line — is another way of disabling them without needing to actually delete them. Many configuration files ship with multiple options commented out so that they can be enabled or disabled, by toggling them between active code and documentation.
[label /etc/nginx/nginx.conf]
...
http {
...
server_names_hash_bucket_size 64;
...
}
...
Save and close the file when you are finished.
Next, test to make sure that there are no syntax errors in any of your Nginx files:
sudo nginx -t
If there aren't any problems, restart Nginx to enable your changes:
sudo systemctl restart nginx
Nginx should now be serving your domain name. You can test this by navigating to http://<^>your_domain<^>, where you should see something like this:
Step 6 – Security Hardening and Optimization
Before proceeding to file management, let's secure and optimize your Nginx installation for production use.
Basic Security Configuration
Edit the main Nginx configuration file:
sudo nano /etc/nginx/nginx.conf
Add these security directives in the http block:
# Hide Nginx version
server_tokens off;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
# Disable server signature
server_tokens off;
# Limit request size
client_max_body_size 10M;
# Timeout settings
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
Performance Optimization
Add these performance optimizations to /etc/nginx/nginx.conf:
# Worker processes (adjust based on CPU cores)
worker_processes auto;
# Worker connections
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
# Gzip compression
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml+rss
application/atom+xml
image/svg+xml;
Test and Apply Configuration
Test your configuration:
sudo nginx -t
If the test passes, reload Nginx:
sudo systemctl reload nginx
SSL/TLS Preparation
Prepare for SSL certificate installation:
# Install Certbot
sudo apt install certbot python3-certbot-nginx -y
# Check if Certbot is working
sudo certbot --version
Step 7 – Getting Familiar with Important Nginx Files and Directories
Now that you know how to manage the Nginx service itself, you should take a few minutes to familiarize yourself with a few important directories and files.
Content
/var/www/html: The actual web content, which by default only consists of the default Nginx page you saw earlier, is served out of the/var/www/htmldirectory. This can be changed by altering Nginx configuration files.
Server Configuration
/etc/nginx: The Nginx configuration directory. All of the Nginx configuration files reside here./etc/nginx/nginx.conf: The main Nginx configuration file. This can be modified to make changes to the Nginx global configuration./etc/nginx/sites-available/: The directory where per-site server blocks can be stored. Nginx will not use the configuration files found in this directory unless they are linked to thesites-enableddirectory. Typically, all server block configuration is done in this directory, and then enabled by linking to the other directory./etc/nginx/sites-enabled/: The directory where enabled per-site server blocks are stored. Typically, these are created by linking to configuration files found in thesites-availabledirectory./etc/nginx/snippets: This directory contains configuration fragments that can be included elsewhere in the Nginx configuration. Potentially repeatable configuration segments are good candidates for refactoring into snippets.
Server Logs
/var/log/nginx/access.log: Every request to your web server is recorded in this log file unless Nginx is configured to do otherwise./var/log/nginx/error.log: Any Nginx errors will be recorded in this log.
How do I secure my Nginx installation?
Follow these security best practices to harden your Nginx installation:
| Security Practice | Implementation | Command/Configuration | Priority |
|---|---|---|---|
| Keep Nginx Updated | Regularly update Nginx and system packages | sudo apt update && sudo apt upgrade nginx |
High |
| Configure Firewall | Use UFW to restrict access to necessary ports only | sudo ufw allow 'Nginx Full' |
High |
| Enable SSL/TLS | Install SSL certificates using Let's Encrypt | sudo certbot --nginx -d your_domain.com |
High |
| Hide Server Information | Prevent Nginx version disclosure | Add server_tokens off; to /etc/nginx/nginx.conf |
Medium |
| Secure Headers | Add security headers to prevent common attacks | Add headers in server block (see example below) | Medium |
| Rate Limiting | Protect against DDoS and brute force attacks | Configure limit_req_zone and limit_req |
Medium |
| Strong Authentication | Use secure passwords for admin interfaces | Implement HTTP basic auth or OAuth | Medium |
| Regular Backups | Backup configuration and web content | sudo cp -r /etc/nginx /backup/nginx-$(date +%Y%m%d) |
Medium |
| Access Control | Restrict access to sensitive directories | Use deny all; or IP whitelisting |
Low |
| Log Monitoring | Monitor access and error logs for suspicious activity | sudo tail -f /var/log/nginx/error.log |
Low |
Example Security Headers Configuration
Add these headers to your server block for enhanced security:
server {
...
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
...
}
Rate Limiting Configuration
Add this configuration to your server block for rate limiting:
server {
...
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
...
}
Frequently Asked Questions (FAQ)
1. How do I start and stop Nginx on Ubuntu 22.04/24.04/25.04?
Use systemctl commands to manage the Nginx service:
# Start Nginx
sudo systemctl start nginx
# Stop Nginx
sudo systemctl stop nginx
# Restart Nginx
sudo systemctl restart nginx
# Reload configuration without stopping
sudo systemctl reload nginx
# Enable Nginx to start on boot
sudo systemctl enable nginx
# Disable Nginx from starting on boot
sudo systemctl disable nginx
2. How can I check if Nginx is running?
Use these commands to verify Nginx status:
# Check service status
sudo systemctl status nginx
# Check if Nginx is listening on ports
sudo netstat -tlnp | grep nginx
# Test configuration
sudo nginx -t
# Check Nginx processes
ps aux | grep nginx
3. How do I configure UFW for Nginx?
UFW provides three Nginx profiles for different security levels:
# Allow HTTP only (port 80)
sudo ufw allow 'Nginx HTTP'
# Allow HTTPS only (port 443)
sudo ufw allow 'Nginx HTTPS'
# Allow both HTTP and HTTPS
sudo ufw allow 'Nginx Full'
# Check UFW status
sudo ufw status
4. What is the default Nginx configuration file on Ubuntu?
The main configuration file is located at /etc/nginx/nginx.conf. Site-specific configurations are stored in:
- Available sites:
/etc/nginx/sites-available/ - Enabled sites:
/etc/nginx/sites-enabled/ - Default site:
/etc/nginx/sites-available/default
5. How do I set up Nginx as a reverse proxy?
Configure a server block in /etc/nginx/sites-available/your-domain:
server {
listen 80;
server_name your-domain.com;
location / {
proxy_pass http://localhost:3000;
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;
}
}
6. How do I troubleshoot Nginx errors?
Check these common troubleshooting steps:
# Test configuration syntax
sudo nginx -t
# Check error logs
sudo tail -f /var/log/nginx/error.log
# Check access logs
sudo tail -f /var/log/nginx/access.log
# Check system logs
sudo journalctl -u nginx -f
# Verify port binding
sudo netstat -tlnp | grep :80
7. What's the difference between Ubuntu 22.04, 24.04, and 25.04 for Nginx?
Key differences include:
| Feature | Ubuntu 22.04 | Ubuntu 24.04 | Ubuntu 25.04 |
|---|---|---|---|
| Nginx Version | 1.18.0+ | 1.24.0+ | 1.26.0+ |
| Support Until | 2027 | 2029 | 2026 |
| Security Updates | Standard | Enhanced | Latest |
| Performance | Good | Better | Best |
| New Features | Basic | Advanced | Cutting-edge |
Conclusion
You now have a fully functional Nginx web server installed and configured on Ubuntu 22.04, 24.04, or 25.04. Throughout this guide, we've walked through the complete process of setting up Nginx, from initial installation using Ubuntu's official repositories to advanced security hardening and performance optimization. You've learned how to configure the UFW firewall to secure your web server, manage the Nginx service using systemd commands, and set up server blocks for hosting multiple domains. The guide has also equipped you with essential knowledge for implementing reverse proxy configurations and troubleshooting common issues through log analysis.
Understanding the version-specific features across Ubuntu releases will help you make informed decisions about your deployment environment. With Nginx's powerful features and optimized performance, your web server is now ready to host websites, serve as a reverse proxy, implement load balancing, and handle high-traffic applications. The security measures and performance tuning options we've covered will ensure your web server remains stable, secure, and efficient in a production environment.
Next Steps
- LEMP Stack: Build a complete application stack with How To Install Linux, Nginx, MySQL, PHP (LEMP stack) on Ubuntu
- SSL/TLS Setup: Secure your site with How To Secure Nginx with Let's Encrypt on Ubuntu
- Reverse Proxy: Configure Nginx as a reverse proxy for your applications