Installing Nginx on Linux is one of the most common tasks you will do after setting up a virtual server. Nginx is a lightweight, fast, and incredibly scalable web server behind a large portion of the world's most trafficked sites today. In addition to providing web content, this web server can also act as a reverse proxy, load balancer, and content cacher. In this comprehensive guide from Rapido Server, you will learn step-by-step how to install, configure and secure Nginx and prepare your website to run.

What is Nginx and how is it different from Apache?

Nginx (pronounced "enginex") was developed in 2004 with the aim of solving the famous C10k problem of managing ten thousand connections at the same time. Unlike the Apache web server, which traditionally creates a separate process or thread for each connection, Nginx uses an event-driven and asynchronous architecture. This architecture allows Nginx to handle a large number of simultaneous connections with very little memory consumption.

For this reason, Nginx is especially popular for serving static content such as images, CSS files, and JavaScript, as well as as a reverse proxy in front of dynamic applications. In many modern architectures, Nginx sits at the forefront, routing requests to back-end services such as Node.js, Django, or PHP-FPM.

Tip: Before starting, make sure you have a Linux server. If you haven't got a server yet, you can order a suitable VPS through the Buy Virtual Server page.

Installing Nginx on Linux (Ubuntu, Debian and CentOS)

The process of installing Nginx on Linux is slightly different depending on the distribution, but in all cases it is simple and fast. First of all, update the system package list to install the latest versions.

For Debian-based distributions like Ubuntu and Debian, we use the apt package manager:

apt update
apt install nginx -y

For Red Hat-based distributions such as CentOS, AlmaLinux, and Rocky Linux, use dnf or yum:

dnf install epel-release -y
dnf install nginx -y

After the installation is finished, enable and run the Nginx service so that it comes up automatically both now and after subsequent server restarts:

systemctl start nginx
systemctl enable nginx

To make sure the service is running properly, check its status:

systemctl status nginx

If the output contains active (running), Nginx is successfully installed and running. Now just enter the IP address of the server in the browser to see the default Nginx welcome page.

Getting to know the structure of Nginx configuration files

One of the important points in installing Nginx on Linux is to understand the structure of folders and configuration files. The main configuration file is in the /etc/nginx/nginx.conf path, but the best practice is to write the settings for each site in separate files. The common structure in Ubuntu and Debian is as follows:

  • /etc/nginx/nginx.conf — Main and global configuration file.
  • /etc/nginx/sites-available/ — Location of settings for all sites.
  • /etc/nginx/sites-enabled/ — symbolic links to active sites.
  • /var/www/html/ — Default path for web files.
  • /var/log/nginx/ — storage location for access and error logs.

In Red Hat distributions, instead of the sites-available and sites-enabled folders, the /etc/nginx/conf.d/ folder is usually used, where any file with the .conf extension is loaded automatically. Each site configuration unit is called a server block that specifies how Nginx should respond to requests from a specific domain or port.

Creating the first Server Block for the website

To host a website, you need to create a dedicated server block. Let's say you want to launch a site with the example.com domain. First, create a folder for site files:

mkdir -p /var/www/example.com/html
chown -R www-data:www-data /var/www/example.com/html

Then create a new configuration file:

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

Put the following content in it. This configuration defines a basic server block for serving static content:

server {
    listen 80;
    server_name example.com www.example.com;
    root /var/www/example.com/html;
    index index.html index.htm;

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

Now activate this site by creating a symbolic link in the sites-enabled folder:

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

Before restarting, always check the correctness of the configuration to avoid typing errors:

nginx -t

If message syntax is ok and test is successful are displayed, apply the changes with reload command. Unlike restart, the reload command loads the new configuration without breaking current connections:

systemctl reload nginx

Configure Nginx as a reverse proxy

One of the most powerful uses of Nginx is to act as a reverse proxy in front of web applications. Suppose a Node.js application is running on port 3000 and you want users to access it through the domain. In this case, your server block will be as follows:

server {
    listen 80;
    server_name app.example.com;

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

In this configuration, the proxy_pass command directs all requests to the back-end application, and the proxy_set_header headers convey information such as the actual user address and the underlying protocol to the application. These headers are essential for many frameworks to function properly. With this pattern, you can manage dozens of different applications behind a single Nginx server.

Free HTTPS activation with Let's Encrypt

Nowadays, having an SSL certificate is a must for every website. With the free Certbot tool, you can get a valid certificate from Let's Encrypt and activate it on Nginx. First, install Certbot and its Nginx plugin:

apt install certbot python3-certbot-nginx -y

Then get the certificate and automatically apply it to the Nginx configuration with one command:

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

Certbot asks a few simple questions at runtime, including your email and whether you want HTTP traffic automatically redirected to HTTPS. By selecting the redirect option, the security of your site is guaranteed. Let's Encrypt certificates expire every 90 days, but Certbot installs a systemd timer that automatically renews. You can simulate the extension to make sure it works:

certbot renew --dry-run

Optimizing Nginx performance and security

After the initial setup, a few tweaks can dramatically improve your site's speed and security. The following table summarizes the most important optimizations:

settingpurposeSuggested amount
gzipCompression of responses and reduction of transmission volumeon
keepalive_timeoutManage persistent connections65
worker_processesNumber of worker processesauto
server_tokensHiding Nginx versionoff

To enable gzip compression, add these lines to the http block of the nginx.conf file:

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml;
gzip_min_length 1024;

Also, for static content such as images and CSS files, setting browser cache headers will make users see the site faster on subsequent visits. Adding security headers like X-Frame-Options and X-Content-Type-Options also prevents common attacks. To read more guides about server administration, visit Rapido Server Articles.

Serving PHP applications with PHP-FPM

One of the most used scenarios in installing Nginx on Linux is running PHP applications such as WordPress, Laravel or other content management systems. Unlike Apache, the Nginx web server does not process PHP itself and leaves it to a service called PHP-FPM (FastCGI Process Manager). First, install PHP-FPM:

apt install php-fpm php-mysql -y

Then in your server block, add a block to process PHP files. Note that the PHP version in the socket path may vary:

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

In this configuration, any request ending in a file with the php extension is sent to the PHP-FPM socket to be processed and the result returned to the user. After adding this block, always first check the configuration with nginx -t and then apply with reload. This separation of duties architecture allows Nginx to simultaneously serve static content at high speed and leave heavy PHP processing to separate processes.

Configure Nginx as a load balancer

When your site's traffic becomes so high that one server is unresponsive, you can use Nginx as a load balancer to distribute requests among multiple back-end servers. To do this, you first define an upstream block that specifies the list of back-end servers:

upstream backend_servers {
    server 10.0.0.11:3000;
    server 10.0.0.12:3000;
    server 10.0.0.13:3000;
}

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://backend_servers;
    }
}

By default, Nginx uses the Round Robin algorithm, which distributes requests among servers in turn. Other algorithms such as least_conn (send to the server with the fewest active connections) and ip_hash (always send a user's requests to the same server) are also available. This feature allows you to scale your site horizontally and have high resistance against a server failure.

Log management and traffic monitoring

Continuous monitoring of logs is an important part of maintaining a healthy web server. Nginx produces two main types of logs: the access log, which records all requests, and the error log, which displays problems. To view incoming requests live:

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

You can also customize the log format to record the information you want, such as response time. Command line tools are very useful for quickly analyzing logs. For example, to find the 10 IP addresses that sent the most requests:

awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -10

This type of analysis helps you identify unusual traffic patterns, attack attempts, or bot behavior. It is also recommended to use logrotate to automatically rotate the logs so that the log files do not become too large and fill up the server's disk space.

Troubleshooting common Nginx problems

You may encounter errors while working with Nginx. The first source for troubleshooting is the error log file:

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

A common 502 Bad Gateway error usually means that the backend application that Nginx proxies to is not running or is listening on the wrong port. A 403 Forbidden error is often caused by incorrect file or folder permissions. The 404 Not Found error indicates that the root path or index file is not set correctly. By carefully checking the logs and running nginx -t before each restart, you can quickly identify and fix most of these problems.

Another important point is to check the status of the server's firewall. Sometimes Nginx works fine but the firewall blocks ports 80 and 443 and users cannot access the site. In Ubuntu, with the ufw tool, you can open these ports:

ufw allow 'Nginx Full'
ufw reload

The "Nginx Full" profile allows both HTTP and HTTPS ports. Also, if you make a configuration change and don't see the result, remember that browsers often cache responses; So for accurate testing, use browser incognito mode or curl command line tool to see actual server response. The habit of systematically checking the log, configuration and firewall makes troubleshooting a fast and reliable process.

Frequently asked questions

What prerequisites do I need to install Nginx on Linux?

You only need a Linux server with root access or a user with sudo permission. Ubuntu, Debian, CentOS and AlmaLinux distributions all support Nginx and it only takes a few minutes to install.

What is the difference between reload and restart in Nginx?

The reload command loads the new configuration without breaking current connections and is ideal for routine changes. But restart completely stops and restarts the service, which causes a momentary interruption of connections; So use reload as much as possible.

Can I host multiple websites on one Nginx server?

yes By creating a separate server block for each domain in the sites-available folder and enabling it, you can run dozens of independent sites on a single server. This capability is called name-based virtual hosting.

How valid is a free Let's Encrypt SSL certificate?

Let's Encrypt certificates are valid for 90 days, but Certbot automatically renews them before they expire. Therefore, after the initial setup, there is no need for manual intervention and your site will always have a valid certificate.