Official service for cobs using NGinx. Nginx commands that you are responsible for knowing the Nginx configuration file

One of the most popular web servers

Nginx accounts for its great popularity among web proxy servers due to its productivity. The server has a lot of advantages, but setting it up will be easy for a beginner. We would like to help you understand the files, syntax, and also configure the basic parameters of Nginx.

Directory hierarchy

All server configuration files are stored in the /etc/nginx directory. In addition, there are a number of folders located in the middle of the directory, as well as modular configuration files.

cd /etc/nginx
ls -F
conf.d/koi-win naxsi.rules scgi_params uwsgi_params
fastcgi_params mime.types nginx.conf sites-available/win-utf
koi-utf naxsi_core.rules proxy_params sites-enabled /

If you've used Apache, you'll be familiar with the sites-enabled and sites-available directories. They indicate the configuration of sites. The created files are saved in a permanent directory. The sites-enabled folder is required to save the configuration of only active sites. To link them, a symbolic message is required between the folders. Configurations can also be saved in conf.d. In this case, when Nginx is launched, the file with the .conf extension will be read as new. When writing configuration files, type the code without errors and correct the syntax. All other files are installed in /etc/nginx. The configurator contains information about specific processes, as well as additional components.

The main Nginx configuration file is nginx.conf.

It reads all configuration files, combining them into one, when the server starts. Open the file for help:

sudo nano /etc/nginx/nginx.conf

The following rows will appear on the screen:

user www-data;
worker_processes 4;
pid /var/run/nginx.pid;
events (
worker_connections 768;
#Multi_accept on;
}
http(
. . .

Persha - some hidden news about Nginx. The phrase user www-data indicates the user who runs the server. The pid directive indicates whether PID processes assigned to the internal wiki are de-routed. The worker_processes row shows how many processes Nginx can run simultaneously. In addition, you can enter logs here (for example, the error log is listed as a function of the error_log directive). The events section is expanded below. VIN is required to process the server connection. After this, the http block is reinstalled.

Structure of the Nginx configuration file

A simpler file formatting structure will help you navigate the web server configuration more easily. It is divided into structural blocks. Configuration details of the http block are divided into levels using closed blocks. The stench of the demise of the authorities from Batkovsky, the one in whom to grow up. This block saves most of the server configuration. They are divided into server blocks, in the middle of which there are different locations.

If you are setting up an Nginx server, remember that the lower the configuration block is expanded, the fewer elements will be affected by power and danger. The presence file has a large number of options that can change the operation of the server. You can set compressed files to be sent to the client, for example. For whom write the parameters:

gzip on;
gzip_disable "msie6";

Please be aware that the same parameter can take on different values ​​in different blocks. Set it first, then re-select the parameter as required. If I don’t want to change the value, the program will set the values ​​in automatic mode.

The remaining rows in the nginx.conf file are:

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

Please note that the location and server blocks are saved in this file. You specify the settings for the URL and specific files. This structure is necessary to support a modular configuration structure. In the middle, you can create new directories and files for different sites. In addition, you can group similar files. After review, you can close the nginx.conf file.

Virtual blocks

They are analogous to virtual hosts in Apache. Blocks in the server section include the characteristics of other sites that are running on the server. In the sites-available folder you will find a file in the server block, which is responsible for the calculations. In the meantime, you can find out the required data that may be needed when servicing sites.

cd sites-available
sudo nano default
server (
root/usr/share/nginx/www;
index index.html index.htm;
server_name localhost;
location/(
try_files $uri $uri //index.html;
}
location/doc/(
alias/usr/share/doc/;
autoindex on;
allow 127.0.0.1;
deny all;
}
}

The commentary was neatly tidied up at the well-known butt. The whole thing was divided for ease of use. In the middle of the server blocks, settings are added, placed near the figure of the bow:

This block is located behind the additional include directive at the end of http, written in the nginx.conf file. Following the root directive, a directory is designated where content will be distributed to the site. Your program will search for files that the correspondent will ask for. The way to get started is: /usr/share/nginx/www. Nginx reinforces rows and directives one after another. If you can’t put down the signs, so many rows can be read as one. To specify the rules that will be included in the index, use the index directive. The server will check them in order of re-inspection. If you are interested in the required pages, please turn to index.html. If this is not the case, then the server will be set to index.htm.

server_name rule

This includes a list of domain names that will be responsible for processing the server block. They can be written as many as possible, separated by spaces. If you put * at the end or at the beginning of the domain, you can put the name with a mask. The star indicates parts of the name. If you enter *.com.ua, then all addresses of the designated domain zone will be placed here. If the addresses fit the description of several directives, then this corresponds to the one that fits everywhere. If there are any escapes, the answer will be to the person who has the mask. Otherwise, the type will be indicated by regular expressions. Server names in regular languages ​​begin with a tilde (~).

Location blocks

Next step, we will have a location block. VIN is required to determine the method of processing the singing drinks. If the resources do not correspond to any other location blocks, then the directives assigned in the arms will be stacked before them. These blocks can include paths to kshtalt /doc/. To establish a new relationship between uri and location, the = sign is closed. With a stoic tilde, you can set the type with regular expressions. You can also set sensitivity to the register by setting ~. If you add a star, the register does not play any role.

Please be careful: if you ask in the same way as the location block, you will be confused and your search will be confused. If not specified, the URI will match the parameters of the location directives. A block with ^ ~ is selected, which matches the URI for the selected block. If this option is not enabled, the server selects the optimal escape and also searches for wikis regular viruses. This is necessary to select one of the corresponding templates. As soon as the truth is found, it will be corrected. In another case, in this way, it will be stuck in front of the URI. However, be aware that Nginx loves more of all types. As there are none, you will begin to search for regular expressions, and then by URI. Parity is determined by the combination of symbols ^ ~.

try_files rule

This is a very useful tool designed to verify the presence of files in the established order. The first one meets the criteria for processing the request. You can use additional parameters to specify how the server should be serviced. The configurator has the following row of settings:

try_files $uri $uri //index.html;

What does that mean? When a request is found that is served by the location block, the server will immediately try to parse the uri as a file. This will be ensured by the change $uri. If there are no types, uri will be organized like a catalogue. You can check your meaning by adding a slash at the end: $ uri /. There may be situations when neither the file nor the directory is found. In this situation, you need to use the file behind it - index.html. The try_files rule freezes the remaining parameter as a fallback option. That's why Denmark file guilty of being in the system. However, if no escapes were found, Nginx turned the side of the problem. To put it in, write = and amend code:

Additional options

If you set the alias rule, you can serve the pages of the location block and the root directory, for example. If files are required from doc, they will be fed from /usr/share/doc/. In addition, the autoindex on rule starts listing the server directory for the specified location directive. If you enter the deny and allow rows, you will be able to change access to directories.

Yak visnovok varto say that Nginx is even tighter richly functional tool. In order to get to grips with the principle of your work, it will take time and effort. Once you understand the robot configuration, you will be able to enjoy the capabilities of the programs in the rest of the world.

N ginx is referred to as “engine x” - a cost-free, high-performance HTTP and gateway proxy server that is responsible for engaging some of the largest sites on the Internet. It can be used as a standalone web server and as a gateway proxy server for Apache and other web servers.

As a developer or system administrator who knows everything, you work with Nginx on a regular basis.

This article will look at the most important and frequently used Nginx commands, including Nginx startup, startup, and restart.

Persh nіzh you will honor

All commands must be entered under the name or root and must be used in any current Linux distribution, such as CentOS 7 and Debian 9.

start Nginx

Launching Nginx is easy. Just run the following command:

Sudo systemctl start nginx

Once successful, the team does not see any results.

If you are using a Linux distribution without systemd to run the Nginx type:

Sudo service start nginx

Instead of manually starting the Nginx service, it is recommended to configure it to start when the system is locked:

Sudo systemctl enable nginx

Zupiniti Nging

Stop Nginx will quickly stop all Nginx worker processes if the connection is enabled.

To start Nginx, wiki one of the following commands:

Sudo systemctl stop nginx sudo service stop nginx

restart Nginx

The restart parameter is a quick way to boot up and start the Nginx server.

Vikorize one of the following commands to restart Nginx:

Sudo systemctl restart nginx sudo service restart nginx

This team is where you will undoubtedly be victorious most often.

restart Nginx

You need to restart Nginx immediately if you make changes to its configuration.

The restart option is to install a new configuration, launch new work processes with the new configuration and correctly terminate the old work processes.

To restart Nginx, vikorize one of the following commands:

Sudo systemctl reload nginx sudo service reload nginx

Testing Nginx configuration

Whenever you make changes to the Nginx server configuration file, it is recommended to check the configuration before restarting or restarting the service.

Use this command to check your Nginx configuration for any syntactic or system errors:

Sudo nginx -t

The visnovok will look something like this.

Nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

If there are any pardons, the team will supervise the report.

Marvel at Nginx status

To check the Nginx service state, use the following command:

Sudo systemctl status nginx

The symbol will look something like this:

* Nginx.service - nginx - high performance web server Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled) Drop-In: /etc/systemd/system/nginx.service.d ` -nofile.conf Active: active (running) since Mon 2019-04-22 10:21:22 MSK; 10h ago Docs: http://nginx.org/en/docs/ Process: 1113 ExecStart = /usr/sbin/nginx -c /etc/nginx/nginx.conf (code = exited, status = 0 / SUCCESS) Main PID : 1183 (nginx) Tasks: 4 Memory: 63.1M CPU: 3min 31.529s CGroup: /system.slice/nginx.service | -1183 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.con | -1184 nginx: worker process | -1185 nginx: worker process ` -1186 nginx: worker process

Change the Nginx version

Sometimes you may need to know the version of your Nginx so that you can troubleshoot the problem or determine if the song function is available.

You can check your Nginx version by running:

Sudo nginx -v nginx version: nginx/1.14.0 (Ubuntu)

Option -V will display the Nginx version at once based on possible configuration.

Sudo nginx -V

visnovok

In this article we showed you the actions of the most important Nginx commands. If you want to learn more about the Nginx command line, check out the Nginx documentation

Nginx is a popular and productive web server and gateway proxy server.

Nginx has a lot of advantages, thanks to its customization it is easy to use and will not be lost on newbies. This guide will help you understand the basic parameters, syntax, and files of Nginx.

Note: Kerivnitstvo is installed on Ubuntu 12.04.

Nginx directory hierarchy

Nginx stores configuration files in the /etc/nginx directory.

This directory contains several more directories and modular configuration files.

cd /etc/nginx
ls -F

conf.d/koi-win naxsi.rules scgi_params uwsgi_params
fastcgi_params mime.types nginx.conf sites-available/win-utf
koi-utf naxsi_core.rules proxy_params sites-enabled /

Apache users are already familiar with the sites-available and sites-enabled directories. These directories indicate the configuration of sites. Files are created and saved in sites-available; in sites-enabled only configurations of enabled sites are saved. For this purpose it is necessary to make a symbolic change from sites-available to sites-enabled.

The conf.d directory can also be modified to save configurations. A file with the .conf extension will be read when Nginx starts. The syntax of such files is not to blame.

Below are all the files that are saved in / etc / nginx, which includes information about the configuration of specific processes and additional components.

The main Nginx configuration file is nginx.conf.

nginx.conf file

The nginx.conf file reads various configuration files and combines them into a single configuration file when the server starts.

Open the file:

sudo nano /etc/nginx/nginx.conf

user www-data;
worker_processes 4;
pid /var/run/nginx.pid;
events (
worker_connections 768;
#Multi_accept on;
}
http(
. . .

The first rows provide hidden information about Nginx. The user www-data row specifies the server, and the server is started after that.

The pid directive specifies where process PIDs will be saved for internal wikis. The row of worker_processes indicates the number of processes that can be supported by Nginx at a time.

Also in this part of the file you can enter logs (for example, the error log is written using the error_log directive).

For hidden information about the server, follow the events section. It handles the Nginx configuration. Followed by the http block. Before you continue to become familiar with web server configurations, you need to understand how to format the Nginx configuration file.

Structure of the Nginx configuration file

The Nginx configuration file is divided into blocks.

The first block is events, followed by http and the main hierarchy of configurations begins.

Configuration details for the http block are divided equally into closed blocks, which reduce power from the block in which they are removed. The http block stores a large part of basic Nginx configurations, which are divided into server blocks, which, in turn, are divided into location blocks.

When setting up Nginx, it is important to remember the following rule: the higher the configuration level, the more blocks there are in this configuration; The lower the configuration, the more individual it is. If the X parameter is liable to get stuck in the server block, then such a parameter needs to be placed in the http block.

Once you take a good look at the file, you will note that there are a lot of options available to control how programs behave as a whole.

For example, to resolve file compression, you need to set the following parameters:

gzip on;
gzip_disable "msie6";

You should enable gzip support to restrict data being sent to the client and enable gzip to Internet Explorer 6 (this browser does not support data compression).

Is it possible that some parameter is to blame for the mother? Different values in several server blocks, then this parameter can be set on great equal, And then re-value it in the middle of the server blocks themselves. As a result, Nginx removes the lower level parameter.

This configuration on the same level eliminates the need to store multiple identical files. In addition, if you forgot to select the parameters for lower level, Nginx simply configures the settings.

The http block in the nginx.conf file ends like this:

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;

This means that the server and location blocks, which indicate the settings of specific sites and the URL, will be saved within this file.

This allows you to support a modular configuration architecture, in which you can create new files to serve new sites. It also allows you to group similar files.

Close the nginx.conf file. Now you need to adjust the settings of the other sites.

Nginx virtual blocks

Server blocks in Nginx are analogous to Apache virtual hosts (also called virtual hosts for clarity). Essentially, server blocks are technical characteristics several websites hosted on one server.

In the sites-available catalog you can find the file for the server block, which is supplied with the server. This file contains all the necessary data for maintaining the site.

cd sites-available
sudo nano default

root/usr/share/nginx/www;
index index.html index.htm;
server_name localhost;
location/(

}
location/doc/(

alias/usr/share/doc/;
autoindex on;
allow 127.0.0.1;
deny all;

The file contains very good comments, but in the appendix comments are omitted for simplicity and readability.

The server block includes all the adjustments placed between the curly arms:

server (
. . .
}

This block of placements in the nginx.conf file is close to the end of the http block with the additional include directive.

The root directive specifies the directory in which the site's content will be stored. In this catalog Nginx will search for the required files. For installation, this directory is /usr/share/nginx/www.

Restore respect: all rows will end with a dotted line. This is how Nginx reinforces one directive over another. As a matter of fact, Nginx will read two directives (or several directives) as one directive with additional arguments.

The index directive designates files that will be listed in the index. The web server will check the files in the order in which they were restored. If the same side was not requested, the server block will find and return the index.html file. If it cannot find the entire file, it will try to process index.htm.

server_name directive

The server_name directive contains a list of domain names that will be served by this server block. The number of domains is not shared; Domains in the list of traces are separated by spaces.

The star symbol (*) at the beginning or at the end of the domain specifies a name with a mask, where the star represents parts (or several parts) of the name. For example, the names *.example.com would be similar to the names forum.example.com and www.animals.example.com.

Since querying the URL corresponds to several server_name directives, this is primarily the same, which is completely avoided.

If the addresses do not show any escapes, you will have to look for the names found with a mask, which will end with a star. If you don’t know such a name, you probably avoid regular expressions.

Server names in regular languages ​​begin with a tilde (~). Unfortunately, this topic is beyond the scope of this article.

location blocks

The location / row indicates that the directives in the arms will be stuck to all resources, which are not consistent with any other location blocks.

Such blocks can place uri paths (for example /doc/). To re-establish identity between location and uri, use the = symbol. The symbol ~ establishes a relationship with regular expressions.

The tilde enables the case-sensitive mode, and the tilde with a star enables the case-insensitive mode.

If the request matches the location block, then the server rejects the search and vikoristas the block. If the server does not know the exact location block, it matches the URI with the parameters of the location directives. Nginx select a block in which the symbols ^ ~ and which are escaped from the URI are combined.

Since the ^ ~ option is not selected, Nginx selects the closest option and stops searching for regular viruses to try to select one of the available templates. If you know such a Wislow, then you will find a Vikorist yogo. Since there is no such virus, the vikorist server is found before the URI has been escaped.

In this case, note that Nginx will be exactly the same. Since there are no such similarities, a regular virus searches, and then searches by URI. To change the search priority by URI, select the character combination ^ ~.

try_files directive

The try_files directive is a useful tool that checks the presence of files in a given order and selects the first file found for processing the request.

This allows you to get help additional parameters It means how Nginx is serviced.

The configuration file has the following row:

try_files $uri $uri //index.html;

This means that when asked to be served by the location block, Nginx will immediately try to serve the uri as a file (this behavior is set by the $uri change).

If the server does not detect the value of the $uri, it will try to match the uri as a directory.

Following the slash at the end, the server checks the contents of the directory, for example, $uri/.

If a file or directory is not found, Nginx creates the file according to the rules (in this case, index.html in the root directory of the server block). The try_files directive uses the remaining parameter as a fallback option, which is the file responsible for being in the system.

If the web server does not detect any errors in the previous parameters, you can turn the correction side. For which the sign is one and the pardon code is used.

For example, if the location / block cannot find a resource request, instead of the index.html file, you can turn the 404 warning:

try_files $uri $uri / = 404;

To do this, you need to put a sign of trust and set the code for the payment in the remaining parameter box (= 404).

Additional parameters

The alias directive allows Nginx to serve pages to the location block of the given directory (for example, the position of root).

For example, files uploaded to /doc/ will be served from /usr/share/doc/.

The autoindex on directive allows you to enable Nginx directory listing for a given location directive.

The allow and deny rows control access to directories.

visnovok

The Nginx web server is richly functional and very productive, but its terminology and parameters can be confusing.

Once you understand Nginx configurations and start working with them, you will relinquish all the benefits of this hard and light tool.

Tags:,

The Nginx web server is one of the most popular web servers with very high productivity and fast processing of static requests for clients. With proper configuration, you can achieve even higher productivity from your web server. Nginx can handle static files very well, be it html pages or other types of resources.

In one of the previous articles, we already looked at setting up some basic parameters, in this article I want to focus more on the productivity and preparation of the web server before it rises in the military minds. What's the fuss? Linux distribution, Then today we will look at CentOS, this system is often tested on servers and with Nginx setup, some inconsistencies may arise here. Next we will look at setting up Nginx CentOS, let's talk about how to re-enable http2 support, google pagespeed, and adjust the main configuration file.

In the official repositories of CentOS and Nginx and Win, you can see everything already installed on your system. We would also like the site to operate using the http2 protocol, which allows all data to be transferred to one connection, resulting in greater productivity. To work via http2, you will need to set up an SSL certificate, but this is already written about in the statistics of the Lets Encrypt Nginx certificate. That's not all. To switch from the original SSL to HTTP2.0, most browsers are currently using the ALPN protocol, and they are supported starting with OpenSSL 1.02. That's because only OpenSSL 1.01 is in the repositories. Therefore, we need to install the version of Nginx compiled from OpenSSL 1.02. For this you can use Broken Repo:

sudo yum -y install yum-utils
# Sudo yum-config-manager --add-repo https://brouken.com/brouken.repo

If you are using the EPEL repository, you will need to specify that the Nginx sibling is not required:

sudo yum-config-manager --save --setopt = epel.exclude = nginx *;

Now to install the correct version of Nginx, type:

sudo yum install nginx

The remaining version of Nginx 1.13.2 will be installed, with continued support from ALPN. Now let's move on to the adjustments.

2. Setting up Nginx

Let us first take a look at the structure of the configuration file. At first glance, we might all get very confused here, but everything would be logical there:

global options
events()
http(
server (
location()
}
server()
}

First, go to the global options, which set the basic parameters of the program, for example, what type of computer will be launched and the number of processes. Next section events This describes how Nginx will respond to input connections, then there is a section http, This is how everything is fully configured to the http protocol. She has a section server, This section is representative of the same domain, in the server section there is a section location, Everyone knows that the URL itself is asked for, it is important to remember that it is not the file on the server, as in Apache, but the URL itself that is asked.

The main global settings will be made in the /etc/nginx/nginx.conf file. Next, we’ll take a look at what we will change and what values ​​need to be set. Let's talk about global options:

  • user- the server, depending on the name of whichever server is launched, must be the owner of the directory with the files of the site, and in the name of which it is necessary to run php-fpm;
  • worker_processes- the number of Nginx processes that will be launched will need to be installed equal to the number of cores you have, for example, I have 4;
  • worker_cpu_affinity- this parameter allows you to attach the skin process to a particular processor core, set the value to auto, so that the program itself selects what and how to attach it;
  • worker_rlimit_nofile- the maximum number of files that can be opened by the program, each connection requires at least two files and each process will be indicated by you number of connections, so the formula is as follows: worker_processes * worker_connections * 2, parameter worker_connections let's take the little bits apart;
  • pcre_jit- enable this parameter to speed up the processing of regular expressions using additional JIT compilation;

In the events section, you can configure two parameters:

  • worker_connections- the number of connections for one process may be sufficient for processing input connections. First of all, we need to know how many of these input connections are received, for which the statistics behind the IP_server address / nginx_status are visible. How to turn it on, let's take a look below. The Active Connections row has a large number of active connections with the server, and you also need to ensure that connections with php-fpm are also respected. Next, click on the accepted and handled fields, first displaying the completed connections, and then displaying the number of accepted ones. The meaning of the guilt remains the same. If they break up, it means the connection doesn’t happen. Marvel at the butt, the first picture is a problem, the other is order. For my optimal configuration, the figure may be 200 connections (800 in total, based on 4 processes):

  • multi_accept- allows the program to accept a number of connections at once, which also speeds up the work, with a high number of connections;
  • accept_mutex- set the value of this parameter to off, so that all processes immediately receive notifications about new problems;

It is also recommended to use the use epoll directive in the events section, as this effective method Processing input connections for Linux, but this method is still behind the scenes, so I don’t want to add it manually. Let's take a look at a few more parameters from the http section:

  • sendfile- change the method of sending data sendfile. The most effective method for Linux.
  • tcp_nodelay, tcp_nopush- sends headers and body in one package, works in threes;
  • keepalive_timeout- client connection support timeout, if you don’t have a lot of scripts, then it will last 10 seconds, you can set the value for how long it takes for the client to connect to the server;
  • reset_timedout_connection- open the connection after a timeout.
  • open_file_cache- cache information about in closed files. For example, open_file_cache max = 200000 inactive = 120s; max - maximum number of files in cache, cache hour.
  • open_file_cache_valid- if you need to check the relevance of files. For example: open_file_cache_valid 120s;
  • open_file_cache_min_uses- cache only files that have been opened a specified number of times;
  • open_file_cache_errors- remember file changes.
  • if_modified_since- I will set how the if-modified-since headers will be processed. Following this heading, the browser can display a 304 response if the page has not changed since you last viewed it. Possible options - do not send - off, send when the hour is exactly running - exact, send when the hour is running exactly or more - before;

This is how the nginx conf setup will look like:

User nginx;
worker_processes 4;
worker_cpu_affinity auto;
worker_rlimit_nofile 10000;
pcre_jit on;
error_log /var/log/nginx/error.log warn;
load_module "modules/ngx_pagespeed.so";
events (
multi_accept on;
accept_mutex off;
worker_connections 1024;
}
http(
sendfile on;
tcp_nopush on;
tcp_nodelay on;
open_file_cache max = 200000 inactive = 20s;
open_file_cache_valid 120s;
open_file_cache_errors on;
reset_timedout_connection on;
client_body_timeout 10;
keepalive_timeout 65;
include /etc/nginx/sites-enabled.*.conf
}

3. Setting up http2

I will not describe in detail the setup of the server section, since having already installed Nginx in Ubuntu in the article and there is not much to add here, setting up SSL is a big topic and will also be considered in this article. To set up http2, you need SSL as well. Next, simply pass the listen directive to your server section:

listen 194.67.215.125:443 default_server;

listen 194.67.215.125:443 http2 default_server;

axis like this in a simple way You can enable http2 if the correct version of Nginx is installed before the cym.

4. Adjust PageSpeed

Google Pagespeed is an Nginx module that includes various optimizations to ensure that pages are viewed more quickly, the web server runs more efficiently, and users do not experience discomfort. This includes caching, optimization of html code, optimization of images, integration of javascript and css code and much more. Everything is on par with Nginx, which is more effective than if you were working in PHP. But there is one shortcoming here, the module displays the Last Modified header.

On the right, PageSpeed ​​installs a long cache line for all files, and adds a hash to the file name. So the speed of resource consumption will be much higher, since the browser will only fetch the files with the new hash, and LastModified will be removed so that users can make changes to any file that will be changed. Now let’s look at how to install the module. We will have to collect some of the output codes.

It’s important to install the tools for assembly right away, if you don’t install them, then you’ll remove them and won’t know how to work:

yum install wget gcc cmake unzip gcc-c++ pcre-devel zlib-devel

Download and unpack the Nginx output for your version, for example 1.13.3:

wget -c https://nginx.org/download/nginx-1.13.3.tar.gz
# Tar -xzvf nginx-1.13.3.tar.gz

Setting up the nginx server does not include reassembling and replacing programs with similar components, but simply vikoryst and outputs for assembling the module. Download and unpack Weekend PageSpeed:

wget -c https://github.com/pagespeed/ngx_pagespeed/archive/v1.12.34.2-stable.zip
# Unzip v1.12.34.2-stable.zip

Download and unpack the PageSpeed ​​optimization library into the folder with the module's output codes:

cd ngx_pagespeed-1.12.34.2-stable /
# Wget -c https://dl.google.com/dl/page-speed/psol/1.12.34.2-x64.tar.gz
# Tar -xvzf 1.12.34.2-x64.tar.gz

Download and unzip OpenSSL 1.02:

wget -c https://www.openssl.org/source/openssl-1.0.2k.tar.gz -O /opt/lib/$OPENSSL.tar.gz
# Tar xvpzf openssl-1.0.2k.tar.gz

Now we need to pick up the module. The most obvious options available in Nginx threads are:

And now we go to the folder with Nginx, select all the options, the --add-dynamic-module option for PageSpeed, OpenSSL and try to download:

cd nginx-1.13.3
# ./Configure --prefix = /etc/nginx --sbin-path = /usr/sbin/nginx --modules-path = /usr/lib64/nginx/modules --conf-path = /etc/nginx/nginx .conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --pid-path=/var/run/nginx .pid --lock-path=/var/run/nginx.lock --http-client-body-temp-path=/var/cache/nginx/client_temp --http-proxy-temp-path=/var/cache /nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path= /var/cache/nginx/scgi_temp --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --wit h-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --with-cc-opt = " - O2 -g -pipe -Wall -Wp, -D_FORTIFY_SOURCE = 2 -fexceptions -fstack-protector-strong --param = ssp-buffer-size = 4 -grecord-gcc-switches -m64 -mtune = generic "--with -ld-opt=--with -openssl=$HOME/openssl-1.0.2k --add-dynamic-module=$HOME/ngx_pagespeed-1.12.34.2-stable$(PS_NGX_EXTRA_FLAGS)
#make

If everything was divided correctly, then the output is the ngx_pagespeed.so module in the obj folder, which you need to copy to the /etc/nginx/modules folder:

cp ngx_pagespeed.so /etc/nginx/modules/ngx_pagespeed.so

Let's create a folder for the cache:

mkdir -p /var/ngx_pagespeed_cache
# Chown -R nginx: nginx /var/ngx_pagespeed_cache

Now add the following line to enable the module in /etc/nginx/nginx.conf:

load_module "modules/ngx_pagespeed.so";

A Web server based on nginx is an excellent way to improve the productivity of Web sites. The speed of processing static content simply has no equal: it easily captures thousands of overnight connections and can be easily optimized and adjusted to suit any configuration. However? Acting as a front-end for Apache, nginx is the most powerful part of the entire Web infrastructure, so nginx security must be given special attention.

This article is a kind of summary, or, if you want, a summary of all nginx security technologies. It will not have a theory, a description of the basics of setting up a Web server or anything else. Instead, you will find practical material that describes all the basic steps that you need to follow in order to properly stop Web server thefts.

installation

The nginx package is available in precompiled views for any distribution. However, by creating a server on your own, you can create one that is more compact and reliable, and you also have the ability to change the order of the Web server in order to eliminate persistent script caddies.

Change the Web server privacy order

Download nginx output from the file src / http / ngx_http_header_filter_module.c and find the next two rows:

static char ngx_http_server_string = "Server: nginx" CRLF;
static char ngx_http_server_full_string = "Server:" NGINX_VER CRLF;

Replace them with this symbol:

static char ngx_http_server_string = "Server:] [Web Server" CRLF;
static char ngx_http_server_full_string = "Server:] [Web Server" CRLF;

We've seen all the nginx modules you didn't use.

Several nginx modules are connected to the Web server right before compilation, and any of them is fraught with potential insecurity. Perhaps, in the future, a vulnerability will be discovered in one of them, and your server will be under threat. By enabling unnecessary modules, you can significantly reduce the risk of such a situation.

Vikonai collect for additional offensive commands:

# ./Configure --without-http_autoindex_module --without-http_ssi_module
#make
# Make install

This way you remove nginx from behind the included (and in most cases branded) SSI (Server Side Includes) and Autoindex modules. To find out which modules can be safely removed from the Web server, run the configure script with the '-help' flag.

preparing nginx.conf

After installing nginx, configure the trace. On the sides of the magazine there will already be material that describes this process, but we will finish with those statistics and talk about ways to improve server security.

Enable display of the server version on all social media pages

Add the line "server_tokens off" to the nginx.conf file. You can use nginx to receive information about the type and version of the Web server on the pages that is generated in response to the client's request.

Mood protection from the stack view

Add the following rows to the server section:

# Vi /etc/nginx/nginx.conf

# Maximum buffer size for saving client power
client_body_buffer_size 1K;
# Maximum buffer size for saving client data headers
client_header_buffer_size 1k;
# The maximum body size specified by the client is specified in the Content-Length field of the header. Since the server is responsible for maintaining the encroachment of files, this value must be increased
client_max_body_size 1k;
# Quantity and size of buffers for reading the large header of the client request
large_client_header_buffers 2 1k;

Pay attention to the large_client_header_buffers directive. In order to save the row of URIs, nginx sees that the buffer size is equal to the size of the memory side (for x86 - 4 KB). The buffers are reset every time when, upon completion of processing, the connection switches to the keep-alive state. Two 1 KB buffers can save URIs to just 2 KB, which helps combat bots and DoS attacks.

To increase productivity, add the following rows:

# Vi /etc/nginx/nginx.conf

# Timeout when reading the body of the client
client_body_timeout 10;
# Timeout when reading client request header
client_header_timeout 10;
# Timeout, at the end of any keep-alive connection with the client will not be closed on the server side
keepalive_timeout 5 5,
# Timeout when transmitting the signal to the client
send_timeout 10;

Control the number of one-hour connections

To protect the Web server from re-hosting and try to create a DoS attack, add the following lines to the config:

# Vi /etc/nginx/nginx.conf

# We describe the zone (slimits) in which the sessions will be saved. A zone with a size of 1 MB can save approximately 32,000 units, and the size can be set to 5 MB.
limit_zone slimits $binary_remote_addr 5m;
# Sets the maximum number of one-hour connections for one session. Essentially, this number sets the maximum number of connections per IP
limit_conn slimits 5;

The first directive is located in the HTTP section, the other - in the location section. If the number of connections goes beyond the limits, the client receives a “Service unavailable” notification with code 503.

Allow only people to connect to your domain

Attackers can use bots to scan and search for leaked Web servers. Have the bots simply go through the IP address ranges, looking for the 80 ports that are open, and use the HEAD command to retrieve information about the web server (or the head end). You can easily forget such a scan by blocking the download to the server by IP address (add it to the location subsection):

# Vi /etc/nginx/nginx.conf

if ($host!~^(host.com | www.host.com)$) (
return 444;
}

Connect the number of available distribution methods to the Web server

Some bots are using various methods to reach the server to test the type and/or penetration, but RFC 2616 clearly states that the Web server is not required to implement all of them, and methods that are not supported may simply not become obsolete. Today, only the GET (requesting the document), HEAD (requesting the server headers) and POST (requesting the publication of the document) methods are deprived, so all the others can be easily included by adding the below row to the server conf section Iguration file:

# Vi /etc/nginx/nginx.conf

if ($request_method! ~ ^ (GET | HEAD | POST) $) (
return 444;
}

bots are being updated

Another method of blocking bots, scanners and other malicious objects for a specific type of client (user-agent). It is not very effective, since most bots mow down all legitimate browsers, and in some cases it turns brown:

# Vi /etc/nginx/nginx.conf

# Blocked managers are attracted
if ($http_user_agent ~ * LWP::Simple | BBBike | wget) (
return 403;
}
# Actions and types of bots are blocked
if ($http_user_agent ~ * msnbot | scrapbot) (
return 403;
}

Block referrer spam

If your site publishes Web logs in a hidden view, you can easily become a victim of Referrer spam (if spam bots are sent to your server, including in the referrer header the addresses of the site being advertised). This type of spam can easily rank up the SEO ratings of an Internet site, so it needs to be blocked as a matter of course. One way to do this is to add most of the words that appear in the addresses of advertising sites to a blacklist.

# Vi /etc/nginx/nginx.conf

# Server section
if ($ http_referer ~ * (babes | forsale | girl | jewelry | love | nudit | organic | poker | porn | sex | teen))
{
return 403;
}

block hotlink

Hotlink - the inclusion in the side of an image (other content) from another site. In essence, this is a crime, since the images, having wasted more than one year of your free time, are not only easily victorious to others, but also create an attack on your Web server, without pointing to another scammer. To combat the desire, you need to work so that the images are only given to the client in the same way that they are already on the site (in other words, the header of the referrer query is responsible for retaliating against the name of your site). Add the following lines to the server section of the nginx.conf configuration file (host.com is the address of your website):

# Vi /etc/nginx/nginx.conf

location/images/(
valid_referers none blocked www.host.com host.com;
if ($invalid_referer) (
return 403;
}
}

As an alternative, you can configure the server to send a special banner with information about theft in place of the requested image. To do this, replace the row “return 403” with the row:

rewrite^/images/uploads. *\. (gif | jpg | jpeg | png) $ http://www.host.com/banned.jpg last

Protect important directories from third parties

Like any other Web server, nginx allows you to regulate access to directories based on IP address and passwords. This ability can be used to hide certain parts of the site from outside eyes. For example, to expose the URI to the outside world:

# Vi /etc/nginx/nginx.conf

location/uploads/(
# Allows access only to machines in the local network
allow 192.168.1.0/24;
# Raises all others
deny all;
}

Now the documents in the uploads directory can only be accessed by local users. To set a password, you will need to click on more steps. From now on, you need to create a password file that is private for nginx and add the necessary accounts to your account (as an example to admin):

# Mkdir /etc/nginx/.htpasswd
# Htpasswd -c /etc/nginx/.htpasswd/passwd admin

# Vi /etc/nginx/nginx.conf

location/admin/(
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd/passwd;
}

New koristuvachs can be added using an additional offensive command:

# Htpasswd -s /etc/nginx/.htpasswd/passwd koristuvach

wikirist SSL

If your site handles private customer data, such as credit card numbers, passwords for other services, or provides access to other important information, which can be used by third parties, about encryption. Nginx works well with SSL, and its capabilities cannot be lacking.

To configure SSL encryption using nginx, please visit Vikonati kilka simple crumbs. You must first create a certificate using the following command sequence:

# Cd /etc/nginx
# Openssl genrsa -des3 -out server.key 1024
# Openssl req -new -key server.key -out server.csr
# Cp server.key server.key.org
# Openssl rsa -in server.key.org -out server.key
# Openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

Then describe the certificate in the nginx configuration file:

# Vi /etc/nginx/nginx.conf

server (
server_name host.com;
listen 443;
ssl on;
ssl_certificate /etc/nginx/server.crt;
ssl_certificate_key /etc/nginx/server.key;
access_log /etc/nginx/logs/ssl.access.log;
error_log /etc/nginx/logs/ssl.error.log;
}

After this you can restart the Web server:

# /Etc/init.d/nginx reload

Naturally, without support from the side of the Web site itself, it will work without any problems.

Other ways

Set the correct values ​​for system variables

Open the file /etc/sysctl.conf and place it in the following row:

# Vi /etc/sysctl.conf

# Protect against smurf attacks
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Protect against incorrect ICMP messages
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Protect against SYN flood
net.ipv4.tcp_syncookies = 1
# Protected by routing from the device
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
# Protection against spoofing
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Mi is not a router
net.ipv4.ip_forward = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
# Enable ExecShield
kernel.exec-shield = 1
kernel.randomize_va_space = 1
# We are expanding the range of available ports
net.ipv4.ip_local_port_range = 2000 65000
# Increasing the maximum size of TCP buffers
net.ipv4.tcp_rmem = 4096 87380 8388608
net.ipv4.tcp_wmem = 4096 87380 8388608
net.core.rmem_max = 8388608
net.core.wmem_max = 8388608
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_window_scaling = 1

Place the root directory of the Web server on the visible section

By placing the root directory of the Web server in the vision of the partition and protecting the new location of any linked files and device files, and protect the system from those who can deny access to the root of the Web server. So the entry in the /etc/fstab file looks something like this:

/ Dev / sda5 / nginx ext4 defaults, nosuid, noexec, nodev 1 2

Chroot/jail nginx

Whatever the case, the nix system allows you to close the add-on in the isolated middle of the viconn. In Linux, you can use the technologies KVM, Xen, OpenVZ and VServer, in FreeBSD - Jail, in Solaris - Zones. If both of these technologies are not available, you can put nginx in a classic chroot, whichever you want is more powerful, otherwise more attackers will be able to interfere.

Install SELinux rules for nginx protection

A good alternative to isolated media is Viconnaya local systems detected and escaped intrusions such as SELinux or AppArmor. If properly tuned, they can defeat the attacks of an evil Web server. By default, they are not configured for robots in connection with nginx, prote within the framework of the project SELinuxNginx(Http://sf.net/projects/selinuxnginx/) Rules have been created for SELinux that can be used as needed. You can only download and install:

# Tar -zxvf se-ngix_1_0_10.tar.gz
# Cd se-ngix_1_0_10 / nginx
#make
# /usr/sbin/semodule -i nginx.pp

firewall settings

If you install nginx on machines that are ready for high deployment, you are often left without a single edge service running on the server. To secure the server, create a very small set of rules that will open 80, 110 and 143 ports (as, of course, nginx is also guilty of using IMAP / POP3 proxies) and close calls Everything is different in this world.

Limit the number of connections behind a firewall

For a website that isn't very popular, it's a good idea to combine a number of tests from the same IP address into one. This can protect you from various types of DoS attacks and brute force. On Linux, you can use the standard iptables / netfilter state module:

# Iptables -A INPUT -p tcp --dport 80 -i eth0 \
-m state --state NEW -m recent --set
# Iptables -A INPUT -p tcp --dport 80 -i eth0 \
-m state --state NEW -m recent --update \
--seconds 60 --hitcount 15 -j DROP

The rules reduce the limit on the number of connections from one IP per network to 15. The same can be done using pf:

# Vi /etc/pf.conf

webserver_ip = "1.1.1.1"
table persist
block in quick from
pass in on $ ext_if proto tcp to $ webserver_ip \
port www flags S/SA keep state \
(Max-src-conn 100, max-src-conn-rate 15/60,\
overload flush)

In addition to the limit on the number of consecutive connections (15 per hour), this rule sets an additional limit on the number of one-hour connections at 100.

PHP settings

If you use nginx in connection with PHP, don’t forget to tune it. The axis is responsible for looking at the configuration file /etc/php/php.ini of the stolen server:

# Vi /etc/php/php.ini

# Unsafe functions can be disabled
disable_functions = phpinfo, system, mail, exec
# Maximum hour for a script
max_execution_time = 30
# Maximum hour, how can you use the script to process the data?
max_input_time = 60
# Maximum amount of memory visible to the skin script
memory_limit = 8M
# The maximum size of data that the script uses in addition to the POST method
post_max_size = 8M
# Maximum file size
upload_max_filesize = 2M
# Don't show PHP scripts to the developers
display_errors = Off
# Enable Safe Mode
safe_mode = On
# Enable SQL Safe Mode
sql.safe_mode = On
# It is allowed to include external commands only in this catalog
safe_mode_exec_dir = / path / to / stolen / directory
# Protected from the flow of information about PHP
expose_php = Off
# Vedemo logs
log_errors = On
# Protects the storage of deleted files
allow_url_fopen = Off

visnovki

By keeping the descriptions in the article recommendations, you will prevent more Web server thefts. Please be aware that not all technologies will suit your configuration. For example, brute force protection, based on reducing the size of the buffers that nginx sees when processing client requests, can lead to a drop in productivity, and in some cases, to failures in processing requests. Decreasing the number of connections will cause a strong impact on productivity for medium-loaded websites, otherwise it will cause waste, since the site has a low flow of drains. Always check how the changes you made affect the productivity and efficiency of the Web page.

About the hero of the day

Nginx is one of the most productive and popular Web servers in the world. Based on data from Netcraft, it is used to support more than 12 million websites around the world, including such mastodons as Rambler, Yandex, Begun, WordPress.com, Wrike, vkontakte.ru, megashara.com, Librusek Taba.ru. Competent architecture, based on multiplexing using system clicks select, epoll (Linux), kqueue (FreeBSD) and memory management mechanisms based on pools (small buffers from 1 to 16 KB), allows nginx not to gives guidance under even high navantazhennyami, vitrifying over 10,000 one-hour connections (this is the name of the C10K problem). Originally written by Igor Sysoev for the Rambler company and launched in 2004 under a BSD-like license.

In contact with