Nginx is a web server and reverse proxy with high performance, scalability, and reliability. Developed in 2004 as an alternative to Apache, and is widely used for delivering high-traffic content. Nginx handles many connections with low resource usage, ideal for static content. Its load-balancing features distribute requests across servers for improved performance and high availability. Nginx can be used to cache, and speed up the delivery of dynamic content.
Thanks to its many features and benefits, Nginx has become a popular choice for developers, system administrators, and organizations looking to scale content.
In this article, we will examine in detail the process of installing and configuring Nginx in the Ubuntu 18.04 LTS, 20.04 LTS or 22.04 LTS distribution. You will learn how to create virtual hosts and install a Firewall. Step-by-step instructions and example configuration files will be provided to make the process easier to understand.
Nginx System Requirements
To set up Nginx on the Ubuntu Server, the system requirements will vary depending on the traffic load and the content served by the web server. However, here’s a basic guideline for minimal system requirements:
Minimal System Requirements for Nginx on Ubuntu Server:
Operating System: Ubuntu Server LTS (Long Term Support) version, such as Ubuntu 18.04 LTS, 20.04 LTS or 22.04 LTS. CPU: 1 GHz or higher. Memory: At least 512 MB of RAM; 1 GB or more is recommended for better performance. Storage: A minimum of 1 GB of free disk space for Nginx and its logs. Consider more space for website content and user uploads. Network: Reliable network connection with an assigned IP address. Dependencies: Make sure you have `curl`, `gnupg2`, `ca-certificates`, `lsb-release`, and other dependencies that might be needed for additional Nginx modules.
Recommended System Requirements for High Traffic Sites:
CPU: 2 GHz dual-core or higher. Memory: 2 GB of RAM or more. Storage: Solid State Drive (SSD) with at least 5 GB of free space or more, depending on the content volume. Network: High-bandwidth network interface, preferably with a 1 Gbps connection or faster.
Keep in mind that these are general recommendations. For a high-traffic, production-level server, you would need to adjust the requirements based on the expected load and resource usage. Monitoring tools can help you assess and plan the capacity needs as your site grows.
Install Nginx on Ubuntu
Because Nginx is already in the Ubuntu repositories, its installation is possible through the apt package system.
To access the updated package lists, we must update the local package index, since this is our first interaction with the apt package system in this session. After this, we can install Nginx.
Update packages
Connect via SSH to your server with administrator rights.
Update the package index and update all existing packages by running the following commands:
$sudo apt update sudo apt upgrade
Once the apt procedure is accepted, Nginx and all required dependencies will be installed on your server.
We will use Nginx repositories to install packages. Let’s install the stable version of Nginx.
If you encounter this error during the repository installation process:
$apt install nginx Reading package lists... Done Building dependency tree... Done Reading state information... Done The following additional packages will be installed: fontconfig-config fonts-dejavu-core libfontconfig1 libgd3 libmaxminddb0 libnginx-mod-http-geoip2 libnginx-mod-http-image-filter libnginx-mod-http-xslt-filter libnginx-mod-mail libnginx-mod-stream libnginx-mod-stream-geoip2 libtiff5 libxpm4 libxslt1.1 nginx-common nginx-core Suggested packages: libgd-tools mmdb-bin fcgiwrap nginx-doc ssl-cert The following NEW packages will be installed: fontconfig-config fonts-dejavu-core libfontconfig1 libgd3 libmaxminddb0 libnginx-mod-http-geoip2 libnginx-mod-http-image-filter libnginx-mod-http-xslt-filter libnginx-mod-mail libnginx-mod-stream libnginx-mod-stream-geoip2 libtiff5 libxpm4 libxslt1.1 nginx nginx-common nginx-core 0 upgraded, 17 newly installed, 0 to remove and 5 not upgraded. Need to get 185 kB/2438 kB of archives. After this operation, 7677 kB of additional disk space will be used. Do you want to continue? [Y/n] Y Ign:1 http://ge.archive.ubuntu.com/ubuntu jammy-updates/main amd64 libtiff5 amd64 4.3.0-6ubuntu0.7 Err:1 http://ge.archive.ubuntu.com/ubuntu jammy-updates/main amd64 libtiff5 amd64 4.3.0-6ubuntu0.7 404 Not Found [IP: 217.147.227.66 80] Unable to correct missing packages. E: Failed to fetch http://ge.archive.ubuntu.com/ubuntu/pool/main/t/tiff/libtiff5_4.3.0-6ubuntu0.7_amd64.deb 404 Not Found [IP: 217.147.227.66 80] E: Aborting install.
Run the following command and then repeat the Nginx installation process:
To check the presence of the Nginx service in startup, you can use the command:
$sudo systemctl is-enabled nginx
If the response is “enabled”, then the service is added to startup and will start automatically when the system starts. If “disabled” is displayed, then you need to run the command:
$sudo systemctl enable nginx
Let’s check the web server’s operating status and make sure that it is successfully installed and added to startup by running the following command:
$sudo systemctl status nginx
If the Nginx service is not running, you can start it with the following command:
$sudo systemctl start nginx
Below are the basic control commands that will be useful when working with an installed web server:
Function
Team
Starting the Nginx service
sudo systemctl start nginx
Stopping the Nginx service
sudo systemctl stop nginx
Restarting the Nginx service
sudo systemctl restart nginx
Restarting the Nginx configuration
sudo systemctl reload nginx
Checking the Nginx status
sudo systemctl status nginx
Checking the Nginx configuration
sudo nginx -t
For a more detailed study of the available commands and parameters of the Nginx service, you can use the `nginx -h` command and `man nginx`. The `nginx -h` command displays quick help on the commands that can be used in the console, while `man nginx` provides a complete description and guidance on using Nginx. Both commands can be useful when working with the Nginx web server.
Checking Nginx operation
Let’s check if Nginx is listening on port 80. To do this, run the following command: `sudo netstat -antp | grep nginx`. If the command is not found, you need to install the required set of utilities by running the following command: `sudo apt install net-tools`.
$sudo apt install net-tools Reading package lists... Done Building dependency tree... Done Reading state information... Done The following NEW packages will be installed: net-tools 0 upgraded, 1 newly installed, 0 to remove and 6 not upgraded. Need to get 204 kB of archives. After this operation, 819 kB of additional disk space will be used. Get:1 http://ge.archive.ubuntu.com/ubuntu jammy/main amd64 net-tools amd64 1.60+git20181103.0eebece-1ubuntu5 [204 kB] Fetched 204 kB in 0s (434 kB/s) debconf: delaying package configuration, since apt-utils is not installed Selecting previously unselected package net-tools. (Reading database ... 64763 files and directories currently installed.) Preparing to unpack .../net-tools_1.60+git20181103.0eebece-1ubuntu5_amd64.deb ... Unpacking net-tools (1.60+git20181103.0eebece-1ubuntu5) ... Setting up net-tools (1.60+git20181103.0eebece-1ubuntu5) ... debconf: unable to initialize frontend: Dialog debconf: (No usable dialog-like program is installed, so the dialog based frontend cannot be used. at /usr/share/perl5/Debconf/FrontEnd/Dialog.pm line 78.) debconf: falling back to frontend: Readline Scanning processes... Scanning linux images... Running kernel seems to be up-to-date. No services need to be restarted. No containers need to be restarted. No user sessions are running outdated binaries. No VM guests are running outdated hypervisor (qemu) binaries on this host.
If you open your browser now and enter your server’s IP address in the address bar, you will see Nginx running. However, before you can start using the server, you still need to configure it.
This completes the Nginx installation, now we can start configuring it and installing the necessary software.
Installing and configuring Firewall is an important step in ensuring server security. Thanks to this, you can close all ports except the necessary ones, such as 22 (SSH), 80 (HTTP) and 443 (HTTPS). The first protocol is necessary for connecting to a remote server, and the second and third are necessary for communication between the client and the site. The main difference between HTTP and HTTPS is that HTTPS is an encrypted protocol, thanks to an SSL certificate, which ensures the security of data transmission.
To install the UFW (Uncomplicated Firewall) utility on the server, run the following command:
$sudo apt install ufw
After installing the UFW utility, you need to add rules for opening ports 22, 80 and 443, which we specified earlier. To do this, run the following commands:
After the rules are added, you can enable the firewall with the command:
$sudo ufw enable
Now UFW will automatically start every time the server boots.
To verify that the firewall settings have been applied correctly, you must enter the following command:
$sudo ufw status
If all settings are made correctly, the output will list only the ports that we need for work: 22 (SSH), 80 (HTTP) and 443 (HTTPS). If any port is missing or not specified, then you need to check your firewall settings and make the necessary changes.
For a more detailed study of configuring the ufw firewall, it is recommended to refer to the article “How to Install and Set Up UFW Firewall on Ubuntu”, which contains detailed information and usage examples.
Setting up Nginx
Nginx is a powerful and versatile web server known for its high performance, stability, and low resource consumption. Configuring Nginx properly is crucial for optimizing your website’s speed, security, and reliability. In this guide, we’ll cover the basics of Nginx configuration, including setting up virtual hosts, securing your server, and fine-tuning performance settings to ensure your web server runs smoothly and efficiently.
Nginx directories
Understanding how these directories and files work is very important for setting up and managing the Nginx web server.
Listed below are some directories and files related to setting up and managing the Nginx web server:
/var/www/html is the directory where the Nginx home page is located, as mentioned above.
/etc/nginx – the main directory where Nginx configuration files are located.
/etc/nginx/nginx.conf – Nginx main configuration file containing basic settings.
/etc/nginx/conf.d/ contains configuration files that can be included in the main Nginx configuration file (nginx.conf) using the include directive. These files may contain server settings, request routing, and other settings for specific virtual hosts or applications.
/etc/nginx/sites-enabled – directory containing active virtual hosts of the Nginx server.
/etc/nginx/sites-available – directory containing virtual host configuration files for each site. Links to these files should be located in the /etc/nginx/sites-enabled directory.
/etc/nginx/snippets – a directory containing so-called snippets that can be connected to the main configuration of the Nginx server if necessary.
/etc/nginx/modules contains additional modules that can be installed on the Nginx web server to extend its functionality. Each module is usually represented by a separate .so (shared object) file. This directory can also contain configuration files associated with installed modules.
The main file is the nginx.conf configuration
Web server administration includes changing and maintaining configuration files.
To view the contents of the main nginx.conf configuration file, you can use any text editor, such as Nano or Vim. For example, to open a file in Nano, you can use the following command:
$sudo nano /etc/nginx/nginx.conf
After opening the file, you can make the necessary changes in the server settings. At the same time, it is important to avoid mistakes so that the server continues to work correctly.
After executing the command, the Nginx server configuration file will open, which is divided into modules. By default, it looks like this:
Great, this information has already been provided in a previous answer. It might be more helpful to add more details and examples for each of the sections:
The main Nginx configuration file (/etc/nginx/nginx.conf) consists of several sections, each of which is responsible for certain aspects of the server. The general file structure looks like this:
$global options events { events {} http{ server { location{} } server {} } mail {}
Global options are responsible for general Nginx settings. For example, in this section, you can set logging settings or security settings.
The `events` section contains settings related to events occurring on the network, such as connections or read/write requests.
The `http` section is responsible for the web server settings and must contain at least one `server` section. Each `server` block defines settings for a specific website. For example, you can specify the port on which the server is running or settings for processing requests.
The `location` section can only be located inside the `server` section and contains settings only for a specific request. It can define, for example, how to handle requests to a specific URL.
The `mail` section contains settings for the mail proxy server.
Before looking at the options, you need to pay attention to the line syntax in the configuration file, which looks like this:
$parameter value additional_value...;
For example, the `listen` parameter specifies the port on which Nginx will listen for requests, and the `root` parameter specifies the path to the website’s root directory. Each line must end with a semicolon “;” and all open curly braces “{” must be closed by “}”.
Now, having become familiar with the global structure, we can move on to studying the parameters.
Below are some global options to consider once you are familiar with the general structure of the configuration file:
user: defines the user on whose behalf the program will run.
worker_processes: sets the number of processes required for the program to run in parallel. The number of processes should not exceed the number of cores in the system. If the auto parameter is set, the program will automatically determine this number.
pid: defines the pid file of the program.
worker_rlimit_nofile: Sets the maximum number of files the program can open. This parameter is calculated as the product of worker_processes * worker_connections * 2.
Global options have been reviewed, but there are not many of them, and they do not attract that much interest. However, the most interesting options for optimization are those found in the events section:
worker_connections – this parameter determines how many connections the program can simultaneously process on one process. The maximum number of users that can connect to the server at the same time can be obtained by multiplying the value of worker_processes by this parameter. For optimal performance, it is recommended to set the value between 1024 and 4048.
multi_accept – setting the parameter to on allows you to accept multiple connections at the same time, which increases the speed. The off-parameter limits accept only one connection at a time.
use – this parameter specifies how to work with the network stack. The default is poll, but for optimal performance on Linux, it is recommended to use poll.
Next, we move on to the most significant section – http, this section has many more options implemented:
sendfile – to send data, use the send file method, the parameter value is on.
tcp_nodelay and tcp_nopush allow you to send headers and the beginning of a file in one packet. The value of the parameters is on.
keepalive_timeout – time to wait before the keepalive connection is closed. The default is 65 seconds, but can be reduced to 10 seconds.
keepalive_requests – maximum number of keepalive connections from one client. It is recommended to set the value to 100.
reset_timedout_connection – disconnect connections after a timeout. The value of the on parameter.
open_file_cache – cache information about open files. The setting line looks like this: open_file_cache max=200000 inactive=20s. The max parameter specifies the maximum number of files in the cache, and the inactive parameter specifies the caching time.
open_file_cache_valid – indicates after what time the information should be deleted from the cache. For example, open_file_cache_valid 30s.
open_file_cache_min_uses – cache information about files that have been opened at least the specified number of times.
open_file_cache_errors – cacheProvide information about missing files. The value of the on parameter.
We looked at the main parameters that will help increase Nginx performance. Next, we’ll move on to the server and location sections, which will be useful when setting up virtual hosts.
Setting Gzip compression
Content compression is an integral part of website optimization, as it reduces the size of downloaded data and speeds up site loading. However, enabling this option adds additional load to the server’s processor. To enable content compression in the http section, you need to add the appropriate parameter:
$gzip on;
This directive can also be used in the server section to apply only to a specific virtual domain. Then you configure the compression settings using the following options:
gzip_min_length – sets the minimum page length in bytes at which compression is used. For example, you can set the value to 1000 (1 KB).
gzip_proxied – specifies whether requests proxied by the server should be compressed. The value “any” means that all requests should be compressed.
gzip_types – defines the file types that need to be compressed. For example: text/plain, application/xml, application/x-javascript, text/javascript, text/css, text/json.
gzip_disable “msie6” – disables compression for clients using the IE6 browser.
gzip_comp_level – sets the compression level, which can be set in the range from 1 to 10. Level 1 means minimal compression and level 10 means maximum.
Setting up virtual hosts
Virtual hosts are used to host multiple websites on a server. Since all requests come to the same server IP address, nginx determines what content to serve based on the domain. For nginx to know which domain corresponds to which content, virtual hosts must be configured. It is customary to place each host in a separate file, where the host settings are located in the server section. This does not violate the logic of the configuration file structure, since all files from sites-enabled are imported into the http section.
Let’s look at an example configuration for a website:
listen <port number> indicates the port on which the server listens for connections, 80 is the standard port for HTTP requests. If necessary, you can add the default-server option, which allows the server to open this domain if the domain was not specified in the request.
root /var/www/unixweb/data/www/unixweb.info – this is the directory where the site files are stored.
index index.php is the page that will be displayed by default when a visitor enters the site.
server_name is the domain name of the site, which is specified in this directive.
access_log is a file for recording a log of requests to the server. It can be configured both globally in the http section and for a specific file type in the location.
error_log is a web server error log that can be configured for different levels of detail: warn – maximum level, crit – only critical errors.
You are already familiar with the basics of setting up a virtual host, but in addition to this there is another important section – location. With its help, you can configure the processing of requests for specific files and directories on the server. The syntax for setting location is as follows:
$ location / {}
The location directive allows you to configure the server’s behavior for specific directories and files using an address, which can be either a direct query relative to the server root or a regular expression preceded by a “~” character. Below are possible directives that can be used in the location block:
allow – allows access to the location for users, “all” – for all users, or you can specify an IP or subnet.
deny – denies access to the location to all users, or you can specify an IP or subnet.
try-files – tries to open files in a specific order and opens the first file found. For example, the try_files $uri $uri/ /index.php?$args; first tries to open $uri, then index.php including the $args variable which is equal to the arguments in the query string.
expires – sets the browser caching time for the served element, for example, max – unlimited time, 1d – one day, 1h – one hour, 10s – 10 seconds.
Many other directives can be used in the Nginx configuration file that can be useful in setting up the server. For more detailed information about directives and their use, it is recommended to consult the official documentation.
Below are two examples of configuration using the “location” directive.
This location construct configures server behavior for files with the following extensions: jpg, jpeg, gif, png, svg, mp3, ogg, mpeg, mpg, avi, webp, zip, gz, bz2, rar, swf, js, and css. It indicates that when requesting these files, you need to set the maximum caching time in the browser (expires max), which allows you to speed up the loading of the site.
Example 2:
$ location ~ /*\.(ini|log|sql) { deny all; }
This directive includes a regular expression that blocks access to any files with the extensions “ini”, “log” and “sql”. If a user tries to access a file with one of the specified extensions, they will be denied access.
This setting denies access to PHP scripts in certain directories (uploads, wflogs, w3tc-config, files) and their subdirectories. Regular expressions are used for this. Also, for these requests, writing to the access_log and log_not_found log files is disabled.
This configuration configures the behavior of the Nginx server when requesting the favicon.ico file, which is often used for the site icon in the browser. In this case, error and access logs for this request will be turned off using the log_not_found and access_log directives with the value off, respectively.
Example 5:
$location ~ /\. { deny all; }
This location directive denies access to any files or folders starting with a dot (for example, .git or .htaccess) in the server root directory.
This Nginx configuration block configures the reverse proxy. All requests arriving at the server are processed along a specific route (location /). They are then redirected to the backend server (specified in the proxy_pass line http://backend-server). The request headers also contain information about the host (Host) and the client’s real IP address (X-Real-IP). This can be useful for monitoring and logging requests on the backend server.
After setting up the site configuration, you need to activate it by creating a symbolic link in the `sites-enabled` directory, which Nginx will read when starting:
After completing the installation and configuration of Nginx, it is recommended to check the configuration for errors to avoid possible problems when starting the server. To do this you can use the command:
sudo nginx -t
This command will check the configuration file for errors and report them if any are found. If no errors are found, you can restart Nginx to apply the new configuration with the command:
sudo systemctl restart nginx
The `sudo systemctl reload nginx` command is used to reload the Nginx web server configuration. When this command is executed, Nginx rereads its configuration file and applies the changes made without interrupting current connections.
sudo systemctl reload nginx
Setting up Nginx is a fairly complex topic and may require additional knowledge. For more detailed information and in-depth understanding, it is recommended to refer to the official Nginx documentation at https://nginx.org/en/docs/
Let’s summarize
In this guide, I explained how Nginx works and the main features that will help you work with an HTML site, and also showed basic methods for protecting your files and directories. However, it is worth keeping in mind that this server setup does not cover all the features of setting up for publishing a site in PHP. If you have any questions or need professional help setting up a server to publish a PHP website, don’t hesitate to contact me.
Do you want to protect your web project from hacker attacks and be confident in its security? I can offer you a professional web server setup with enhanced security. I use advanced technologies that guarantee the safety of your project. My setup will help protect your files and directories from unauthorized access and prevent possible vulnerabilities. Contact me https://unixweb.info/about-the-author/ and I will provide reliable protection for your Internet project!