Nginx configuration file. Tweaking Nginx


This guide gives a basic introduction to nginx and describes some simple tasks that can be accomplished with it. It is assumed that nginx is already installed on the reader's computer. If not, see Installing nginx. This guide describes how to start and stop nginx and reload its configuration, explains how the configuration file is structured, and describes how to configure nginx to serve static content, how to configure a proxy server on nginx, and how to link nginx to a FastCGI application.

Nginx has one main and several worker processes. The main task of the main process is to read and check the configuration and manage worker processes. Worker processes perform the actual processing of requests. nginx uses an event-based model and operating system-specific mechanisms to efficiently distribute requests among worker processes. The number of worker processes is set in the configuration file and can be fixed for a given configuration or automatically set equal to the number of available processor cores (see worker_processes).

How nginx and its modules work is defined in the configuration file. By default, the configuration file is called nginx.conf and is located in the /usr/local/nginx/conf, /etc/nginx or /usr/local/etc/nginx directory.

Start, stop, reload configuration

To start nginx, you need to execute the executable file. When nginx is running, it can be controlled by calling the executable with the -s option. Use the following syntax:

nginx -s signal

Where signal may be one of the following:

  • stop - quick completion
  • quit - smooth termination
  • reopen - reopening log files

For example, to stop nginx processes while waiting for worker processes to finish servicing current requests, you can run the following command:

The command must be executed under the same user under which nginx was launched.

Changes made to the configuration file will not be applied until the command to reload the configuration is manually sent to nginx or it is restarted. To reload the configuration run:

Upon receiving the signal, the main process checks the correct syntax of the new configuration file and tries to apply the configuration contained in it. If it succeeds, the main process starts new worker processes and sends messages to the old worker processes to terminate. Otherwise, the main process rolls back the changes and continues to work with the old configuration. Old worker processes, when commanded to terminate, stop accepting new requests and continue to serve current requests until all such requests have been serviced. After this, the old worker processes are terminated.

You can also send signals to nginx processes using Unix tools, such as the kill utility. In this case, the signal is sent directly to the process with the given ID. The nginx master process ID is written by default to the nginx.pid file in the /usr/local/nginx/logs or /var/run directory. For example, if the main process ID is 1628, to send a QUIT signal that will cause nginx to exit gracefully, you would run:

To view a list of all running nginx processes, the ps utility can be used, for example, as follows:

More information about sending signals to nginx processes can be found in Managing nginx.

Configuration file structure

nginx consists of modules that are configured by directives specified in the configuration file. Directives are divided into simple and block. A simple directive consists of a name and parameters, separated by spaces, and ends with a semicolon (;). A block directive is constructed in the same way as a simple directive, but instead of a semicolon following the name and parameters, it is followed by a set of additional instructions placed inside curly braces (( and )). If a block directive can have other directives set inside curly braces, then it is called a context (examples: events , http , server And location).

Directives placed in a configuration file outside of any context are considered to be in the main context. The events and http directives are located in the main context, the server - in http, and the location - in server.

The part of the line after the # symbol is considered a comment.

Serving static content

One of the important tasks of nginx configuration is serving files such as images or static HTML pages. Let's consider an example in which, depending on the request, files will be distributed from different local directories: /data/www, which contains HTML files, and /data/images, which contains image files. To do this, you will need to edit the configuration file and configure the block server inside the block http with two blocks location.

First, create a /data/www directory and put an index.html file with any text content in it, and also create a /data/images directory and put some image files in it.

Next, open the configuration file. The default configuration file already includes several examples of a server block, mostly commented out. For our current task, it is better to comment out all such blocks and add a new server block:

In general, a configuration file may contain several server blocks, distinguishable by ports where they listening, and by server name. Having determined which server will process the request, nginx compares the URI specified in the request header with the parameters of the location directives defined inside the server block.

In the server block, add a location block like this:

location / ( root /data/www; )

This location block specifies “ / ” as a prefix that is compared to the URI from the request. For matching requests, add the URI to the path specified in the directive root, that is, in this case, to /data/www , the path to the requested file in the local file system is obtained. If there is a match to multiple location blocks, nginx selects the block with the longest prefix. The location block above contains the shortest prefix, length one, and therefore this block will only be used if there is no match with any of the other location blocks.

location /images/ ( root /data; )

It will match queries starting with /images/ (location / is also suitable for them, but the prefix specified there is shorter).

The final server block configuration should look like this:

server ( location / ( root /data/www; ) location /images/ ( root /data; ) )

This is a running server configuration listening on standard port 80 and accessible on the local computer at http://localhost/. In response to requests whose URIs begin with /images/ , the server will send files from the /data/images directory. For example, to a request http://localhost/images/example.png nginx will respond with the file /data/images/example.png . If this file does not exist, nginx will send a response indicating a 404 error. Requests whose URIs do not start with /images/ will be mapped to the /data/www directory. For example, a request to http://localhost/some/example.html will result in the file /data/www/some/example.html being sent in response.

To apply the new configuration, start nginx if it is not already running, or send a reload signal to the main nginx process by running:

In case something is not working as expected, you can try to find out the reason using the access.log and error.log files from the /usr/local/nginx/logs or /var/log/nginx directory.

Setting up a simple proxy server

One of the common uses of nginx is to use it as a proxy server, that is, a server that accepts requests, redirects them to proxied servers, receives responses from them and sends them to the client.

We'll set up a basic proxy server that will serve image requests from the local directory and send all other requests to the proxied server. In this example, both servers will run within the same nginx instance.

First, create a proxy server by adding another server block to the nginx configuration file with the following content:

server ( listen 8080; root /data/up1; location / ( ) )

This will be a simple server listening on port 8080 (previously the listen directive was not specified because the standard port 80 was used) and mapping all requests to the /data/up1 directory on the local file system. Create this directory and put the index.html file in it. Note that the root directive is placed in the server context. This root directive will be used when the location directive chosen to execute the request does not contain its own root directive.

Next, use the server configuration from the previous section and modify it to become a proxy server configuration. In the first location block, add a directive proxy_pass, specifying the protocol, name and port of the proxied server as a parameter (in our case it is http://localhost:8080):

server ( location / ( proxy_pass http://localhost:8080; ) location /images/ ( root /data; ) )

We'll change the second location block, which currently maps requests with the /images/ prefix to files in the /data/images directory, to accommodate requests for images with typical file extensions. The modified location block looks like this:

location ~ \.(gif|jpg|png)$ ( root /data/images; )

The parameter is a regular expression that matches all URIs ending in .gif, .jpg, or .png. The regular expression must be preceded by a ~ character. Relevant requests will be mapped to the /data/images directory.

When nginx selects a location block that will serve a request, it first checks the directives location, specifying prefixes, remembering the location with the longest matching prefix, and then checking the regular expressions. If there is a match with the regular expression, nginx selects the corresponding location, otherwise the previously remembered location is taken.

The final proxy server configuration looks like this:

server ( location / ( proxy_pass http://localhost:8080/; ) location ~ \.(gif|jpg|png)$ ( root /data/images; ) )

This server will filter requests ending in .gif , .jpg or .png and map them to the /data/images directory (by appending the URI to the root directive parameter) and forward all other requests to the proxied server configured above.

To apply the new configuration, send a reload signal to nginx, as described in the previous sections.

Exists a bunch of other directives for further configuration of the proxy connection.

Setting up FastCGI proxying

nginx can be used to redirect requests to FastCGI servers. They can run applications created using a variety of frameworks and programming languages, such as PHP.

The basic nginx configuration for working with a proxied FastCGI server includes the use of the directive fastcgi_pass instead of the proxy_pass directive, and directives fastcgi_param to configure parameters passed to the FastCGI server. Imagine that a FastCGI server is available at localhost:9000. Using the proxy configuration from the previous section as a basis, replace the proxy_pass directive with the fastcgi_pass directive and change the parameter to localhost:9000 . In PHP, the SCRIPT_FILENAME parameter is used to define the name of the script, and the QUERY_STRING parameter passes the query parameters. You will get the following configuration:

server ( location / ( fastcgi_pass localhost:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; ) location ~ \.(gif|jpg|png)$ ( root /data/images; ) )

This will configure a server that will redirect all requests, except requests for static images, to a proxied server running at localhost:9000 using the FastCGI protocol.

R beginner's guide

This guide gives a basic introduction to nginx and describes some simple tasks that can be accomplished with it. It is assumed that nginx is already installed on the reader's computer. If not, see Installing nginx . This guide describes how to start and stop nginx and reload its configuration, explains how the configuration file is structured, and describes how to configure nginx to serve static content, how to configure a proxy server on nginx, and how to link nginx to a FastCGI application.

Nginx has one main and several worker processes. The main task of the main process is to read and check the configuration and manage worker processes. Worker processes perform the actual processing of requests. nginx uses an event-based model and operating system-specific mechanisms to efficiently distribute requests among worker processes. The number of worker processes is set in the configuration file and can be fixed for a given configuration or automatically set equal to the number of available processor cores (see. worker_processes).

How nginx and its modules work is defined in the configuration file. By default, the configuration file is called nginx.conf and located in the directory/usr/local/nginx/conf , /etc/nginx or /usr/local/etc/nginx

To start nginx, you need to execute the executable file. When nginx is running, it can be controlled by calling the executable with the parameter-s . Use the following syntax:

nginx -s signal

Where is the signal may be one of the following:

  • stop - quick completion
  • - re-opening log files

For example, to stop nginx processes while waiting for worker processes to finish servicing current requests, you can run the following command:

nginx -s quit

The command must be executed under the same user under which nginx was launched.

Changes made to the configuration file will not be applied until the command to reload the configuration is manually sent to nginx or it is restarted. To reload the configuration run:

nginx -s reload

Upon receiving the signal, the main process checks the correct syntax of the new configuration file and tries to apply the configuration contained in it. If it succeeds, the main process starts new worker processes and sends messages to the old worker processes to terminate. Otherwise, the main process rolls back the changes and continues to work with the old configuration. Old worker processes, when commanded to terminate, stop accepting new requests and continue to serve current requests until all such requests have been serviced. After this, the old worker processes are terminated.

You can also send signals to nginx processes using Unix tools, such as the utility kill . In this case, the signal is sent directly to the process with the given ID. The nginx main process ID is written to the file by default nginx.pid in /usr/local/nginx/logs or /var/run directory . For example, if the main process ID is 1628, to send a QUIT signal that will cause nginx to exit gracefully, you would run:

kill -s QUIT 1628

To view a list of all running nginx processes, the utility can be used ps , for example, as follows:

ps -ax | grep nginx

More information about sending signals to nginx processes can be found in nginx management.

Configuration file structure

nginx consists of modules that are configured by directives specified in the configuration file. Directives are divided into simple and block. A simple directive consists of a name and parameters, separated by spaces, and ends with a semicolon (; ). A block directive is constructed in the same way as a simple directive, but instead of a semicolon following the name and parameters, it is followed by a set of additional instructions placed inside curly braces (( And ) ). If a block directive can have other directives inside curly braces, it is called a context (examples: events , http , server and location ).

Directives placed in a configuration file outside of any context are considered to be in the context main. Events and http directives placed in context main , server is in http , and location is in server .

Part of the line after the character# is considered a comment.

Serving static content

One of the important tasks of nginx configuration is serving files such as images or static HTML pages. Let's consider an example in which, depending on the request, files will be distributed from different local directories:/data/www , which contains HTML files, and/data/images , containing image files. To do this, you will need to edit the configuration file and configure the block server inside an http block with two location blocks.

First, create a directory/data/www and put the file in it index.html with any text content, and also create a catalog/data/images and put some image files in it.

Next, open the configuration file. The default configuration file already includes several block examples server , mostly commented out. For our current task, it is better to comment out all such blocks and add a new block server:

http(

Server (

In general, a configuration file can contain several blocks server , distinguishable by ports where they listen, and by server name . Having determined which server will process the request, nginx compares the URI specified in the request header with the parameters of the directives location , defined inside the block server.

Add a location block to the server block of the following form:

location/(

Root /data/www;

This location block specifies “ / ” as a prefix that is compared to the URI from the request. For matching requests, add the URI to the path specified in the directive root , that is, in this case, to/data/www , the path to the requested file in the local file system is obtained. If there is a match with multiple blocks location , nginx selects the block with the longest prefix. In the block location The above is the shortest prefix, length one, and therefore this block will only be used if there is no match with any of the other blocks location.

location /images/ (

Root/data;

It will match queries starting with/images/ (location / it is also suitable for them, but the prefix indicated there is shorter).

Final block configuration server should look like this:

server (

Location/(

Root /data/www;

Location /images/ (

Root/data;

This is an already running server configuration listening on standard port 80 and accessible on the local computer at http://localhost/ . In response to requests whose URIs begin with/images/ , the server will send files from the directory/data/images . For example, on requesthttp://localhost/images/example.pngnginx will send a file in response/data/images/example.png . If this file does not exist, nginx will send a response indicating a 404 error. Requests whose URIs do not begin with/images/ , will be mapped to the directory/data/www . For example, as a result of the requesthttp://localhost/some/example.htmla file will be sent in response/data/www/some/example.html.

To apply the new configuration, start nginx if it is not already running, or send a signal reload to the nginx main process by running:

nginx -s reload

In case something does not work as expected, you can try to find out the reason using the files access.log and error.log from the /usr/local/nginx/logs or /var/log/nginx directory.

Setting up a simple proxy server

One of the common uses of nginx is to use it as a proxy server, that is, a server that accepts requests, redirects them to proxied servers, receives responses from them and sends them to the client.

We'll set up a basic proxy server that will serve image requests from the local directory and send all other requests to the proxied server. In this example, both servers will run within the same nginx instance.

First, create a proxy server by adding another block server to the nginx configuration file with the following content:

server (

Listen 8080;

Root /data/up1;

Location/(

This will be a simple server listening on port 8080 (previously the directive listen was not specified because the standard port 80 was used) and displays all requests for the directory/data/up1 on the local file system. Create this directory and put the file in it index.html . Please note that the directive root placed in context server . Such a directive root will be used when the directive location , selected to execute the request, does not contain its own directive root.

Next, use the server configuration from the previous section and modify it to become a proxy server configuration. To the first block location add directive proxy_pass , specifying the protocol, name and port of the proxied server as a parameter (in our case this is http://localhost:8080 ):

server (

Location/(

Proxy_pass http://localhost:8080;

Location /images/ (

Root/data;

We will change the second block location , which currently displays queries with the prefix/images/ to files from the directory/data/images so that it is suitable for requests for images with typical file extensions. Modified block location as follows:

Root /data/images;

The parameter is a regular expression that matches all URIs ending in.gif, .jpg or .png . The regular expression must be preceded by a character~ . Matching requests will be displayed on the catalog/data/images.

When nginx selects a block location , which will serve the request, then first it checks the directives location , setting prefixes, remembering location with the longest matching prefix and then checks the regular expressions. If there is a match with the regular expression, nginx selects the appropriate one location , otherwise the previously remembered one is taken location.

The final proxy server configuration looks like this:

server (

Location/(

Proxy_pass http://localhost:8080/;

Location ~ \.(gif|jpg|png)$ (

Root /data/images;

This server will filter requests ending with.gif, .jpg or .png , and map them to the directory/data/images (by adding a URI to the directive parameter root ) and redirect all other requests to the proxied server configured above.

To apply the new configuration, send a signal reload nginx, as described in previous sections.

There are many other directives for further configuration of the proxy connection.

Setting up FastCGI proxying

nginx can be used to redirect requests to FastCGI servers. They can run applications created using a variety of frameworks and programming languages, such as PHP.

The basic nginx configuration for working with a proxied FastCGI server includes the use of the directive fastcgi_pass instead of a directive proxy_pass , and fastcgi_param directives to configure parameters passed to the FastCGI server. Imagine that the FastCGI server is available at localhost:9000 . Using the proxy server configuration from the previous section as a basis, replace the directive proxy_pass to the fastcgi_pass directive and change the setting to localhost:9000 . In PHP the SCRIPT_FILENAME parameter is used to determine the name of the script, and in the parameter QUERY_STRING request parameters are passed. You will get the following configuration:

server (

Location/(

Fastcgi_pass localhost:9000;

Fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

Fastcgi_param QUERY_STRING $query_string;

Location ~ \.(gif|jpg|png)$ (

Root /data/images;

This will set up a server that will redirect all requests, except requests for static images, to a proxied server running at localhost:9000 , using the FastCGI protocol.

N ginx, pronounced "engine x", is a free, high-performance HTTP and reverse proxy server responsible for loading some of the largest sites on the Internet. It can be used as a standalone web server and as a reverse proxy for Apache and other web servers.

If you are a developer or system administrator, chances are you deal with Nginx on a regular basis.

In this article, we will look at the most important and commonly used Nginx commands, including starting, stopping, and restarting Nginx.

Before you start

All commands must be executed as root or root and should work on any modern Linux distribution, such as CentOS 7 and Debian 9.

Launch Nginx

Starting Nginx is quite simple. Just run the following command:

Sudo systemctl start nginx

If successful, the command does not produce any results.

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

Sudo service start nginx

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

Sudo systemctl enable nginx

Stop Nging

Stop Nginx will quickly stop all Nginx worker processes, even if there are open connections.

To stop Nginx, run one of the following commands:

Sudo systemctl stop nginx sudo service stop nginx

Restart Nginx

The restart option is a quick way to stop and start the Nginx server.

Use one of the following commands to restart Nginx:

Sudo systemctl restart nginx sudo service restart nginx

This is the command you'll probably use most often.

Restart Nginx

You need to restart Nginx whenever you make changes to its configuration.

The reboot option will load the new configuration, start new worker processes with the new configuration, and gracefully shut down old worker processes.

To restart Nginx, use 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 reloading the service.

Use the following command to check your Nginx configuration for any syntax or system errors:

Sudo nginx -t

The output 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 errors, the command will print a detailed message.

View Nginx status

To check the status of the Nginx service, use the following command:

Sudo systemctl status nginx

The output 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 processs

Check Nginx version

Sometimes you may need to know your Nginx version so you can debug an issue or determine if a certain feature is available.

You can check your Nginx version by running:

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

The -V option will output the Nginx version along with the option to configure.

Sudo nginx -V

Conclusion

In this article, we have shown you some of the most important Nginx commands. If you want to learn more about the Nginx command line, visit the Nginx documentation

One of the most popular web servers

Nginx is very popular among web and proxy server users due to its performance. The server has many advantages, but setting it up will be difficult for a beginner. We want to help you understand configuration files, syntax, and setting up basic Nginx parameters.

Directory hierarchy

All server configuration files are located in the /etc/nginx directory. In addition, there are several more folders inside 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 should be familiar with the sites-enabled and sites-available directories. They determine the configuration of sites. The created files are stored in the last directory. The sites-enabled folder is needed to store configurations of only activated pages. To link them, you need a symbolic link between the folders. Configurations can also be stored in the conf.d directory. At the same time, during Nginx startup, each file with the .conf extension will be read anew. When writing configuration files, type the code without errors and follow the syntax. All other files are located 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 that is requested when the server starts. Open the file with:

sudo nano /etc/nginx/nginx.conf

The following lines will appear on the screen:

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

The first is general information about Nginx. The phrase user www-data indicates the user who runs the server. The pid directive shows where PID processes for internal use are located. The worker_processes line shows how many processes Nginx can run simultaneously. In addition, you can specify logs here (for example, the error log is determined using the error_log directive). Below is the events section. It is needed to handle server connections. After it is the http block.

Nginx configuration file structure

Understanding the file formatting structure will help you better understand your web server configuration. It is divided into structural blocks. The http block configuration details are layered using private blocks. They inherit properties from the parent, i.e. the one in which they are located. This block stores most of the server configurations. They are divided into server blocks, inside which location.

When you configure the Nginx server, remember that the lower the configuration block is, the fewer elements will inherit properties and vice versa. The file contains a large number of options that change the operation of the server. You can set compression for files sent to the client, for example. To do this, enter the parameters:

gzip on;
gzip_disable "msie6";

Keep in mind that the same parameter can take different values ​​in different blocks. First set it at the top, then redefine the parameter at the desired level. If the last action is not performed, the program will set the values ​​automatically.

The last lines of the nginx.conf file are:

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

They indicate that the location and server blocks are stored outside of this file. They define settings for URLs and specific files. This structure is necessary to maintain a modular configuration structure. Inside it you can create new directories and files for different sites. In addition, you can group similar files. After consideration, you can close the nginx.conf file.

Virtual blocks

They are analogous to virtual hosts in Apache. The server section blocks include characteristics of individual sites that are located on the server. In the sites-available folder you will find the default server block file. Inside it you can find the necessary data that may be required when maintaining 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;
}
}

In the above example, comments were intentionally removed. This was done for ease of perception. Inside the server blocks there are settings enclosed in curly braces:

This block is placed using the include directive at the end of http, written in the nginx.conf file. The root directive defines the directory where the site content will be located. In it, the program will search for files that the user will request. The default path is: /usr/share/nginx/www. Nginx separates lines or directives from one another using semicolons. If you don't put a punctuation mark, several lines will be read as one. To specify the rules that will be used as an index, use the index directive. The server will check them in the order they are listed. If none of the available pages were requested by the user, index.html will be returned. If it is not there, the server will look for index.htm.

server_name rule

It includes a list of domain names that the server block will need to process. You can enter any number of them, separated by spaces. If you put * at the end or beginning of the domain, you can specify a name with a mask. The asterisk matches part of the name. If you enter *.com.ua, then this will include all addresses of the specified domain zone. If the address matches the description of several directives, then it will respond to the one that fully matches. If there are no matches, the answer will be to the longest name that has a mask. Otherwise, regular expression matching will be performed. Server names that use regular expressions begin with a tilde (~).

Location blocks

Next in line we will have the location block. It is needed to determine how certain requests will be processed. If resources do not match any other location blocks, then the directives specified in parentheses will be applied to them. These blocks may include a path like /doc/. To establish a complete match between uri and location, the = sign is used. By using the tilde, you can match regular expressions. You can also set case sensitivity by putting ~. If you add an asterisk, case does not matter.

Keep in mind: when the request fully matches the location block, it will be used and the search will stop. When the match is incomplete, the URI will be compared to the parameters of the location directives. Use a block with ^~ matching the URI to select the block. If this option is not enabled, the server will select the optimal match and also perform a search using regular expressions. This is necessary to select one of the suitable templates. If a suitable expression is found, it will be used. Otherwise, the previous URI match will be applied. However, keep in mind that Nginx prefers full matches. If they are not there, it will start searching for regular expressions, and then by URI. Search parity is specified by the symbol combination ^~.

try_files rule

This is a very useful tool that can check for the presence of files in a specified order. It uses the first one that matches the criteria to process the request. You can use additional parameters to specify how the server will serve requests. The configurator has this default line:

try_files $uri $uri/ /index.html;

What does it mean? If a request comes in that is served by a location block, the server will first try to treat the uri as a file. This is provided by the $uri variable. When there are no matches, the uri will be treated as a directory. You can check its existence by adding a trailing slash: $uri/. There are situations when neither the file nor the directory will be found. In this case, the default file will be loaded - index.html. The try_files rule uses the last parameter as a fallback. That is why this file must be on the system. However, if no matches are found at all, Nginx will return an error page. To set it, enter = and the error code:

Additional options

If you apply the alias rule, you will be able to serve pages of the location block outside the root directory, for example. When files from doc are needed, they will be requested from /usr/share/doc/. In addition, the autoindex on rule starts listing the server directories for the specified location directive. If you write the deny and allow lines, you will be able to change access to directories.

As a conclusion, it is worth saying that Nginx is a very powerful multifunctional tool. But to understand well the principle of its operation, it will take time and effort. If you understand how configurations work, you can fully enjoy all the features of the program.

Nginx? Purpose, features, settings options - these are things that every web developer should be familiar with in order to test their work.

Let's say a word about nginx

This tool has one main and several worker processes. The first one deals with reading and checking the configuration. Work process management is also under his control. The latter's task is to process incoming requests. Nginx uses an event-based model. Operating system-specific mechanisms are also used to achieve efficient distribution of requests directly between worker processes. Their number is always indicated in the configuration file. The value can be either fixed or set automatically, based on the number of processor cores with which you can work. In nginx, the system and modules are configured using a configuration file. Therefore, if you need to change something, then you need to look for it. It is usually located in the /etc/nginx directive (but the path may change when using other systems) and has a .conf extension.

Startup, reboot and logs

To do this, you need to make the executable file work. Configuring the nginx server is possible only when it is running. Control is carried out by calling the executable file with the -s parameter. To do this, use the following notation:

nginx -s signal

In this case, you can substitute the following commands (must come from the user who launched the tool):

  1. Stop. Used to quickly shut down work.
  2. Reload. The command is needed to reload the configuration file. The point is that any changes will not be applied while the file is running. And for them to take effect, a reboot is necessary. As soon as this signal is received, the main process will begin to check the correctness of the syntax of the configuration file and try to apply the instructions there. If it fails, it will roll back the changes and work with the old settings. If everything happened successfully, then new worker processes will be launched, and the old ones will be sent a request to terminate.
  3. Quit. Used for smooth completion of work. Used if you need to wait until current requests are finished servicing.
  4. Reopen. Close and open log files.

Using Utilities

Processes can also be configured using Unix tools (the kill utility will be considered as an example). They typically use a mechanism to send a signal to the process directly with data. They are linked using ID. This data is stored in the nginx.pid file. Let's say that we are interested in process No. 134. Then for smooth completion we need to send the following information:

kill -s QUIT 1628

Let's say we want to view a list of all running files. We use the ps utility for this. The command will look like this:

ps -ax | grep nginx

That is, as you can see, when using additional tools, it is indicated that it is being used. Now let's focus on how nginx configuration is done.

Configuration file structure

Installing and configuring nginx involves working with modules. They are configured using directives that are specified in the configuration file. They are simple and block. The first type of directive consists of a name and parameters, which are separated by spaces, and are terminated by a semicolon (;). Block has a similar structure. But this directive, instead of ending, contains a set of additional instructions, which are placed in curly braces ((instructions)). If they can contain the names and parameters of other processes, then such constructions are called context. Examples include http, location, and server.

Serving static content

This is one of the most important tasks facing the nginx configuration. By distributing statistical content we mean images and HTML pages (not dynamic). Let's say that we need a one-time job of setting up a nix nginx cluster. Is it difficult to do? No, and let's look at an example. Before starting it, it is necessary to detail the conditions of the task. So, depending on the requests, the files will come from different local directories. So, in /data/www we have HTML documents. And the /data/images directory contains images. Optimal configuration of nginx in this case requires editing the configuration file, in which you need to configure the server block inside http. Two locations will also be used for support.

Implementation: server

So, first we need to create the directories themselves and place files with the necessary extensions in them (you need to add content to html). Then open the configuration file. By default, it already contains several server blocks, which are mostly commented out. To achieve optimal results, this process must be done for all default components. Then we add a new server block using the following code:

The configuration file can work with several such blocks. But they must differ in their names and ports through which data is received.

Implementation: location

Defined inside server:

The presence of the “/” sign is necessary to compare the received data and see if such an address from the processed request is here. If there are no problems, then specify the path /data/www to the required file, which is located on this local system. If there is a match with several blocks, then the one with the longest prefix is ​​selected. In the example given, its length is equal to one, that is, it will be used exclusively if there are no “competitors”. Now let's improve it:

location /images/ (

How can you tell if we are looking for images? Now let’s combine all the developments that were previously made, and the configuration at the moment looks like this:

location /images/ (

This is a working option, which is standard. This server can be accessed on the local computer without any problems if you go to the address: http://localhost/. How will all this work?

How the example works

So, when requests arrive that begin with /images, the server will send files from the corresponding directory to the user. If it is absent, information indicating a 404 error will be transmitted. If nginx is configured on a local computer, then when requesting http://localhost/images/example.png we will receive a file whose location is /data/images/example.png. If you specify one character “/”, the search will be carried out in the /data/www directory. But we only changed the configuration. For it to start working, it needs to be rebooted. To do this, use the nginx -s reload command. If normal operation is not possible, you can look for the cause of the malfunction in the error.log and access.log files located in the /usr/local/nginx/logs directive.

Creating a simple proxy server

One can say regarding nginx - setting up this object is one of the common uses (and quite easy, by the way). It uses the principle of a server that receives requests and then redirects them to the necessary sites. After this, a response is expected from them, which directs them to the one who assigned the task. So let's look at an example of creating a base point. It will handle user requests and provide them with images from the local directory. So, to the http block we add another server with the following content:

Now let me decipher it for you: a simple server is being created. It will listen. If you do not specify listen, the server will run on 80. All requests within the local file system that are directed to the /data/up1 directory will be displayed (of course, it will need to be created before this). To be able to check it, you need to place the index.html file there. By placing the root directive in the server context, we can use location under any conditions (since this removes access restrictions). Now we are working on creating a proxy server. For it to work, we need the proxy_pass directive, for which the protocol, name, and object port will be specified as parameters (for a local connection, this will look like http://localhost:8080). You will get the following result:

proxy_pass http://localhost:8080;

location /images/ (

If you look at the code and analyze it, you may notice that the second location block has been changed. So, in this case it can work with typical image extensions. It could be displayed a little differently like this:

location ~ \.(gif|jpg|png)$ (

root /data/images;

The final proxy server configuration looks like this:

proxy_pass http://localhost:8080/;

location ~ \.(gif|jpg|png)$ (

root /data/images;

It will filter out requests that have the specified extensions at the end and send them to the person who asked for the files. Don't forget that if you want to check the configuration file, you will need to reload it. And believe me, this is the simplest nginx setup. If you open the server configuration file of VKontakte or another large company, they will have more code than words in this article.







2024 gtavrl.ru.