Nginx Commands You Should Know. Troubleshooting Nginx installation and configuration Nginx config file

R beginner's guide

This tutorial gives an initial introduction to nginx and describes some of the simple tasks that can be done 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 config file works, and describes how to set up nginx to serve static content, how to set up 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 validate configuration and manage worker processes. Worker processes perform the actual processing of requests. nginx uses an event-based model and depends on operating system mechanisms for efficient distribution of requests between worker processes. The number of worker processes is specified in the configuration file and can be fixed for a given configuration or automatically set equal to the number of available processor cores (see section 3.3. worker_processes ).

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

To run nginx, you need to execute the executable. Once 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 can be one of the following:

  • stop - fast termination
  • - 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:

nginx -s quit

The command must be run under the same user that nginx was run under.

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

nginx -s reload

Upon receiving the signal main process validates the syntax of the new configuration file and tries to apply the configuration contained in it. If it succeeds, the master process starts new worker processes and sends messages to the old worker processes to terminate. Otherwise, the master process rolls back the changes and continues to work with the old configuration. Old worker processes, when given a command to end, stop accepting new requests and continue to service current requests until all such requests have been serviced. After that, 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 . For example, if the main process ID is 1628, to send a QUIT signal that will gracefully terminate nginx, you would run:

kill -s QUIT 1628

The utility can be used to list all running nginx processes 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 directives. A simple directive consists of a name and parameters separated by spaces, and ends with a semicolon (; ). A block directive has the same structure as a simple directive, but instead of a semicolon, the name and parameters are followed by a set of additional instructions placed inside curly braces (( And ) ). If a block directive can have other directives inside curly braces, then it is called a context (examples: events , http , server and location ).

Directives placed in the 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 a string after a character# considered a comment.

Serving Static Content

One of the important tasks of nginx configuration is serving files like 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 An containing image files. To do this, you 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 directory/data/images and put some image files in it.

Next, open the configuration file. The default config file already includes some 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, the configuration file may contain several blocks server , distinguished according to the ports on which they listen, and by server name . By determining 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 the following form:

location / (

Root /data/www;

This location block defines “ / ” as a prefix that is compared to the URI from the request. For matching requests, by adding 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. If there is a match with multiple blocks location , nginx selects the block with the longest prefix. In the block location above is the shortest prefix, length one, and therefore this block will be used only if there is no match with any of the other blocks location.

location /images/ (

Root/data;

It will match queries starting with/images/ (location / 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 a running server configuration that listens on the standard port 80 and is available on local computer by the address http://localhost/ . In response to requests whose URIs begin with/images/ , the server will send files from the directory/data/images . For example, for a 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 start with/images/ , will be mapped to directory/data/www . For example, as a result of a queryhttp://localhost/some/example.htmla file will be sent in response/data/www/some/example.html .

To apply new configuration, start nginx if it's not already running, or send a signal reload to the main nginx 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, forwards them to proxied servers, receives responses from them, and sends them to the client.

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

First, create the upstream server by adding another block server to the nginx config file with the following content:

server(

Listen 8080;

Root /data/up1;

Location / (

This will be a simple server listening on port 8080 (previously listen was not specified because the standard port 80 was used) and displays all requests for a directory/data/up1 on the local file system. Create this directory and put the file in it index.html . Note that the directive root placed in context server . Such a directive root will be used when the directive location The selected for executing the request does not contain a directive of its own 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 a directive proxy_pass , specifying the protocol, name and port of the proxied server as a parameter (in our case, this http://localhost:8080 ):

server(

Location / (

Proxy_pass http://localhost:8080;

Location /images/ (

Root/data;

We will change the second block location , which is on this moment displays requests with a prefix/images/ on files from a directory/data/images so that it is suitable for image requests with typical file extensions. Changed block location as follows:

Root /data/images;

The argument 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 directory/data/images .

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

The resulting 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 display them on the directory/data/images (by adding a URI to the directive parameter root ) and redirect all other requests to the upstream server configured above.

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

There are many other directives to further configure the proxy connection.

Configuring FastCGI Proxying

nginx can be used to forward 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 directive proxy_pass , and fastcgi_param directives to configure the parameters passed to the FastCGI server. Imagine that the FastCGI server is available at localhost:9000 . Based on the proxy server configuration from the previous section, 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 define 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 for requests for static images, to a proxied server running at localhost:9000 , using the FastCGI protocol.

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 the configuration files, syntax, and setting up the basic parameters of Nginx.

Directory Hierarchy

All server configuration files are located in the /etc/nginx directory. In addition, several more folders are located 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 generated files are stored in the last directory. The sites-enabled folder is needed to store configurations for only enabled 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 the startup of Nginx, each file with the .conf extension will be read in a new one. When writing configuration files, type 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 configuration file for Nginx is nginx.conf.

It reads all configuration files, concatenating them into one requested at server startup. 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 one is general information about Nginx. The phrase user www-data specifies the user who runs the server. The pid directive shows where the PID processes intended for internal use are located. The worker_processes line shows how many processes Nginx can run at the same time. In addition, logs can be specified here (for example, the error log is determined by the error_log directive). Below is the events section. It is needed to handle server connections. After it is the block http.

Nginx configuration file structure

Understanding the file formatting structure will help you better understand the web server configuration. It is divided into building blocks. The http block configuration details are layered by 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, within which locations are located.

When you configure the Nginx server, keep in mind 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 the compression of 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 have different values ​​in different blocks. First, set it at the top, then override the parameter at the desired level. If last action not executed, 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 url addresses and specific files. Such a structure is necessary to maintain a modular configuration structure. Inside it, it will be possible to create new directories, files for various 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. Blocks of the server section include the characteristics of individual sites that are located on the server. In the sites-available folder you will find the server block file, which is the default. Inside it, you can find out 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_namelocalhost;
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 are settings enclosed in curly braces:

This block is placed using the include directive at the end of the http specified in the nginx.conf file. The root directive defines the directory where the content of the site will be located. In it, the program will look for the files that the user will request. The default path is /usr/share/nginx/www. Nginx separates lines or directives from one another with a semicolon. If the punctuation mark is not put down, several lines are read as one. To write 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 was requested by the user, index.html will be returned. If it is not there, then 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 write *.com.ua, then all addresses of the specified domain zone. If the address fits the description of several directives, then it will respond to the one that fits completely. 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 start with a tilde (~).

Location blocks

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

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 matched against the parameters of the location directives. A block with a ^~ combination is used, matching the URI for block selection. If this option is not enabled, the server chooses the best match and also searches using regular expressions. This is necessary to select one of the appropriate 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 present, the search for regular expressions will begin, and then by URI. Search parity is specified by a combination of characters ^~.

try_files rule

This is a very useful tool that can check for the existence of files in a given order. It applies the first matching criteria to process the request. You can use advanced options to specify how the server will serve requests. In the configurator, there is this line by default:

try_files $uri $uri/ /index.html;

What does she mean? If a request arrives 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 is no match for it, the uri will be treated as a directory. You can check for its existence by adding a slash at the end: $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 given file must be in the system. However, if no match is found at all, Nginx will return an error page. To set it, write = and the error code:

Additional options

If you apply the alias rule, you can serve the 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 triggers a listing of server directories for the specified location directive. If you write the deny and allow lines, you can change access to directories.

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

|

Nginx is a free and open source web server that is used to serve websites and applications of any complexity. Nginx is known for its low memory impact, high scalability, and modular, event-driven architecture that can deliver reliable and predictable performance. Nginx works not only as a web server, but also as a load balancer, HTTP caching server and reverse proxy.

Of course, at first it can be difficult to remember all the commands and recommendations for managing the Nginx server. This guide is intended for those who work with Nginx. It covers some basic service management commands, as well as tips for diagnosing and resolving some common problems.

Each section can be used independently, so you can skip sections you don't need. All conditional values ​​in commands are highlighted in red; instead of these values, you can substitute your own data.

Note: This assumes you are running the version of Nginx installed from the default repository on a Debian-like distribution. Some of the commands and directives described in this guide are not available in other distributions or versions of Nginx installed from other sources.

Installing Nginx

Update the package index and then install Nginx:

sudo apt-get update
sudo apt-get install nginx

Checking Nginx Status

To check the status of the web server on the current machine, type:

sudo systemctl status nginx

Nginx autoload

By default, the Nginx service starts automatically. If you want to change this behavior, type:

sudo systemctl disable nginx

To add Nginx to startup again, type:

sudo systemctl enable nginx

Managing the Nginx Service

To stop the Nginx server, enter the following command:

sudo systemctl stop nginx

To start the Nginx server, type:

sudo systemctl start nginx

To stop the service and start it again, type:

sudo systemctl restart nginx

If you have changed the configuration, you can reload Nginx in the current session. Enter the following command:

sudo systemctl reload nginx

Creating a root directory for static content

When creating sites on Nginx, developers often use virtual hosts(or server blocks) are hosts that serve individual sites or domains. To do this, you need to create a document root, a directory top level, which Nginx checks when serving content.

The commands in the block below will create a new root directory, transfer permissions to it to the sudo user, and change the permissions of each subdirectory in a subdirectory under /var/www/.


sudo chown -R $USER:$USER /var/www/example.com/html
find /var/www -type d -exec chmod 775 () \;

In this case, the root directory offers global read and execute permissions. To select other permissions, replace 775 and specify the required permissions.

Remember that access rights should change according to the situation.

Creating a Root Directory for Dynamic Files

If your site uses dynamic modules like PHP-FPM, you may need to transfer permissions on some files to the www-data group. If the group needs write access to the directory, give the group ownership of the directory.

The commands below create a new document root, give it to the www-data group, and change the permissions on each subdirectory under /var/www.

sudo mkdir -p /var/www/example.com/html
sudo chown -R www-data:www-data /var/www/example.com
sudo find /var/www -type d -exec chmod 775 () \;

Enabling and disabling configuration files

To enable the virtual host, you need to create a symlink from the sites-available directory to the sites-enabled directory, which Nginx reads at startup time.

To do this, enter the command:

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

After that, you need to restart Nginx so that the settings are updated.

Troubleshooting a hash table

Nginx uses hash tables to quickly process static data (server names, MIME types). If you have added multiple server names, chances are that the specified server name hash size will not be enough, and you will see the server_names_hash_bucket_size error when you make changes. It can be fixed by editing one value in the /etc/nginx/nginx.conf file.

Open this file:

sudo nano /etc/nginx/nginx.conf

Find the server_names_hash_bucket_size directive in the file. Remove the # symbol to uncomment the line and increase the value of the directive:

http(
. . .
server_names_hash_bucket_size 64 ;
. . .
}

This will increase the size of the Nginx server name hash tables and allow the service to process all the server names you have added. Save and close the file, then restart Nginx to update the settings.

Configuration testing

Every time you make changes to Nginx config files, be sure to run the following command to check for syntax errors:

If there are errors in the configuration, the command output will indicate exactly where they were found. If there are no syntax errors in the configuration files, you will see 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 no errors, you can reload the service:

sudo systemctl restart nginx

Important Nginx Files and Directories

Content

The /var/www/html directory stores all of the site's content (this is the site's root directory). you can change standard settings Nginx and specify other directories in var/www.

Server Configuration

  • /etc/nginx/: Nginx configuration directory (all web server configuration files are stored here).
  • /etc/nginx/nginx.conf: The main configuration file of the web server, where all global settings are located.
  • /etc/nginx/sites-available/default: Default Nginx virtual host. Other virtual hosts should also be stored in the sites-available directory (but they won't work without a symlink in sites-enabled).
  • /etc/nginx/sites-enabled/: This is where the files for enabled virtual hosts are stored. On startup or reboot, Nginx reads the configuration files and links in this directory to build the complete configuration.

Logs

  • /var/log/nginx/access.log: This is the log that logs all Nginx requests (unless the web server configuration says otherwise).
  • /var/log/nginx/error.log: This is the error log.

To access the systemd logs of the Nginx process, run this command:

sudo journalctl -u nginx

Conclusion

This manual has listed general procedures support nginx servers. To learn more about working with Nginx, check out the following tutorials.

Tags:

The Nginx web server is one of the most popular web servers with very high performance and fast handling of static requests from users. At correct setting you can achieve very high performance from this web server. Nginx handles static files very quickly, be it html pages or other types of resources.

In one of the previous articles, we have already considered the configuration of its main parameters, in the same article I want to dwell more on the performance and preparation of the web server for use in combat conditions. As for the Linux distribution, today we will consider CentOS, this system is often used on servers and there may be some difficulties with setting up Nginx. Next, we will consider setting up Nginx CentOS, let's talk about how to enable full support for http2, google pagespeed, and set up the main configuration file.

In official CentOS repositories there is Nginx and it is most likely already installed on your system. But we want the site to work using the http2 protocol, which allows you to transfer all data in one connection, and this increases performance. To work over http2 you need to configure SSL certificate, but this is already covered in the article Obtaining a Lets Encrypt Nginx Certificate. But that is not all. Most browsers now use the ALPN protocol to switch from regular SSL to HTTP2.0, and it has been supported since OpenSSL 1.02. While the repositories only have OpenSSL 1.01. Therefore, we need to install a version of Nginx built with OpenSSL 1.02. Broken Repo can be used for this:

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

If you are using the EPEL repository, then you need to specify that you do not need to take Nginx from it:

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

Now, to install the correct version of Nginx, just type:

sudo yum install nginx

The most latest version Nginx 1.13.2, with full ALPN support. Let's move on to the setup.

2. Setting up Nginx

The first step is to consider the structure of the configuration file. At first glance, everything here may seem very confusing, but everything is quite logical there:

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

First there are global options that set the main parameters of the program, for example, from which user it will be launched and the number of processes. There is a section next. events, which describes how Nginx will respond to incoming connections, followed by a section http, which combines all the settings regarding the operation of the http protocol. It contains a section server, each such section is responsible for a separate domain, the server section contains sections location, each of which is responsible for a specific request URL, note that not a file on the server, as in Apache, but the request URL.

We will make the main global settings in the /etc/nginx/nginx.conf file. Next, consider what exactly we will change and what values ​​it is desirable to set. Let's start with global options:

  • user- the user under whose name the server will be launched must be the owner of the directory with the site files, and php-fpm must be launched on behalf of him;
  • worker_processes- the number of Nginx processes that will be launched must be set exactly as many as you have cores, for example, I have 4;
  • worker_cpu_affinity- this parameter allows you to assign each process to a separate processor core, set the value to auto so that the program itself chooses what and what to attach to;
  • worker_rlimit_nofile - maximum amount files that the program can open, you need at least two files per connection, and each process will have the number of connections you specify, so the formula is: worker_processes* worker_connections* 2, parameter worker_connections we will analyze a little lower;
  • pcre_jit- enable this option to speed up the processing of regular expressions using JIT compilation;

In the events section, you should configure two parameters:

  • worker_connections- the number of connections for one process must be sufficient to process incoming connections. First we need to know how many of these incoming connections there are, for this we look at the statistics at the ip_server/nginx_status address. How to enable see below. In the Active Connections line, we see the number of active connections to the server, you also need to take into account that connections with php-fpm are also counted. Next, pay attention to the fields accepted and handled, the first one displays the processed connections, the second - the number of accepted ones. From values ​​must be the same. If they differ, then there are not enough connections. See examples, the first picture is the problem, the second is the order. For my configuration, the figure of 200 connections may be optimal (800 in total, considering 4 processes):

  • multi_accept- allows the program to accept several connections at the same time, also speeds up the work, with a large number of connections;
  • accept_mutex- set the value of this parameter to off, so that all processes immediately receive a notification about new connections;

It is also recommended to use the use epoll directive in the events section, since this is the most efficient method for handling incoming connections for Linux, but this method is used by default, so I see no reason to add it manually. Consider a few more parameters from the http section:

  • sendfile- use the sendfile data sending method. The most efficient method for Linux.
  • tcp_nodelay, tcp_nopush- sends headers and request body in one packet, works a little faster;
  • keepalive_timeout- timeout for maintaining connection with the client, if you do not have very slow scripts, then 10 seconds will be enough, set the value as long as necessary so that the user can be connected to the server;
  • reset_timedout_connection- disconnect connections after timeout.
  • open_file_cache- cache information about open files. For example, open_file_cache max=200000 inactive=120s; max - the maximum number of files in the cache, caching time.
  • open_file_cache_valid- when 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 the specified number of times;
  • open_file_cache_errors- remember file opening errors.
  • if_modified_since- sets how the if-modified-since headers will be processed. With this header, the browser can get a 304 response if the page hasn't changed since the last time it was viewed. There are options - do not send - off, send if the time exactly matches - exact, send if the time matches 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. http2 setup

I will not describe in detail the configuration of the server section, because I already did it in the article installing Nginx in Ubuntu and I have nothing to add here, configuring SSL is a fairly extensive topic and will also be discussed in a separate article. But to set up http2 you need to have SSL already. Next, just tweak the listen directive in your server section:

listen 194.67.215.125:443 default_server;

listen 194.67.215.125:443 http2 default_server;

like this in a simple way it is possible to enable http2 if the correct version of Nginx was installed before.

4. Setting PageSpeed

Google Pagespeed is an Nginx module that performs various optimizations to make pages load faster, the web server works more efficiently, and users feel comfortable. This includes caching, optimization html code, image optimization, combining javascript and css code and much more. All this is done at the Nginx level, so it's more efficient than if you did it in php. But there is one drawback, the module removes header Last modified.

The fact is that PageSpeed ​​sets a very long caching line for all files, and adds its hash to the file name. This makes resource loading much faster, as the browser will only request files with the new hash, and LastModified is removed so users can see the changes if any file is changed. Now let's look at how to install the module. We will have to build it from source.

First install the build tools, it's very important, if you don't install it, then you will get an error and you won't know what to do:

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

Download and extract the Nginx sources 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 rebuilding and replacing the program from the repository, we just use these sources to build the module. Download and extract the PageSpeed ​​sources:

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

Download and unzip the PageSpeed ​​optimization library into the module source folder:

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 extract OpenSSL 1.02 sources:

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 build the module. First, let's look at the options that the current Nginx is built with:

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

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 done correctly, then at the output you will get the ngx_pagespeed.so module in the obj folder, you need to copy it to the /etc/nginx/modules folder:

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

Create a folder for the cache:

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

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

load_module "modules/ngx_pagespeed.so";

We will work under account regular user with sudo rights. You will also need an installed Nginx web server. If desired, you can install the full LEMP (Linux, Nginx, MySQL and PHP). To install Nginx, just run the following command:

sudo apt-get update sudo apt-get install nginx

Before continuing to read the article, we strongly recommend that you fulfill the above conditions. For example, we will set up two domains on our server. Their names are example.com, test.com. If you do not have two free names available, then just come up with two, and later we will show you how to customize your local server to check their functionality.

Step 1 - Setting Up a New Root Directory

By default, only one virtual host is enabled on your Nginx server. It works with documents at: /usr/share/nginx/html . We'll change this setting because we're most likely to work with the /var/www directory. Nginx does not use this directory by default, as it is against Debian's policy to use packages in the /var/www directory.

But since we are ordinary users, and we rarely encounter package storage issues, we will ignore this policy and set this directory as the root. More specifically, each directory within the root directory must correspond to a separate site. And we will place all site files in the /var/www/site_name/html directory. First, let's create all the necessary subdirectories. To do this, run the following command:

sudo mkdir -p /var/www/example.com/html sudo mkdir -p /var/www/test.com/html

The -p flag tells the shell to create new directories if they don't exist in the specified path. Now we will transfer the rights to this directory ordinary user. Let's use the $USER environment variable to avoid entering our account name. After these steps, we will be able to create files in the /var/www/ directory, but site visitors will not.

sudo chown -R $USER:$USER /var/www/example.com/html sudo chown -R $USER:$USER /var/www/test.com/html

The permissions on the root directory should be set correctly if you haven't corrected the umask value, but we'll fix it just in case:

sudo chmod -R 755 /var/www

We have fully prepared the structure for our server, we can move on.

Step 2 - Create a page template for each site

Let's create a page that will be displayed by default when creating a new site. Create an index.html file in the directory of the first domain:

Nano /var/www/example.com/html/index.html

Inside, we will make the minimum content in order to understand what site we are on. Here is an example content:

Welcome to Example.com!

This is the example.com virtual host!



Save and close the file. Since the second file will have similar content, just copy it:

cp /var/www/example.com/html/index.html /var/www/test.com/html/

Let's make a few changes to it:

Nano /var/www/test.com/html/index.html Welcome to Test.com!

This is the test.com virtual host!



Save and close this file. Now we will see if our sites are configured correctly.

Step 3 - Create virtual host files for each domain

Now we have content for each site, it's time to create virtual hosts(more precisely, in Nginx they are called server blocks, but we will use the term virtual host). By default, Nginx uses one virtual host called default. Let's use it as a template for our configuration. First, we will work out the setting for the first domain, which we will then simply copy and make minimal changes to the second domain.

Creating the first virtual host file

As I said, copy the configuration file default:

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/example.com

Let's open this file with administrator rights:

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

If you omit the comments, the file should look like this:

Server ( listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /usr/share/nginx/html; index index.html index.htm; server_name localhost; location / ( try_files $uri $uri/ =404 ; ) )

Let's start with the listen directive. Only one server block can be set to default_server . A block with this value will serve requests if no matching block was found (a block is everything in the server). We will disable this directive in the default virtual host in order to use the default_server on one of our domains. I will leave this feature enabled for the first domain, but you can move it to the second if you wish.

The next thing we'll do is set up the root directory with the root directive. It should point to the directory where all the documents of your site are located:

Root /var/www/example.com/html;

The note: each Nginx instruction must end with a “;” character.

Server_name example.com www.example.com;

Server ( listen 80 default_server; listen [::]:80 default_server ipv6only=on; root /var/www/example.com/html; index index.html index.htm; server_name example.com www.example.com; location / ( try_files $uri $uri/ =404; ) )

On this basic setup finished. Save and close the file.

Create a second virtual host

To do this, simply copy the settings file for the first site:

sudo cp /etc/nginx/sites-available/example.com /etc/nginx/sites-available/test.com

Open this file with administrator rights

sudo nano /etc/nginx/sites-available/test.com

In this file, we will also start with the listen directive. If you left the default_server option in the first file, then it should be deleted here. It is also necessary to remove the ipv6only=on option, since it is specified for only one address/port combination:

Listen 80; listen[::]:80;

Set the root directory for the second site:

Root /var/www/test.com/html;

Now let's specify the server_name for the second domain:

Server_name test.com www.test.com;

The final setup should look like this:

Server ( listen 80; listen [::]:80; root /var/www/test.com/html; index index.html index.htm; server_name test.com www.test.com; location / ( try_files $uri $ uri/ =404; ) )

Save and close the file.

Step 4 - Activating Virtual Hosts and Restarting Nginx

We've set up our virtual hosts, now it's time to activate them. To do this, you need to create symbolic links to these files and put them in the sites-enabled directory, which Nginx reads at startup. Links can be created with the following command:

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

Nginx will now process these files. But the default virtual host is also enabled, so we get a default_server parameter conflict. You can disable this setting simply by removing the link to the file. The file itself will remain in the sites-available directory, so that we can always return it if necessary.

sudo rm /etc/nginx/sites-enabled/default

There is one more setting that needs to be done in the Nginx configuration file. Open it:

sudo nano /etc/nginx/nginx.conf

You need to remove the comment from one of the lines:

Server_names_hash_bucket_size: 64

This directive is used when a large number of server names are given, or unusually long names are given. For example, if the default value is 32 and the server name is set to "too.long.server.name.example.org", then nginx will refuse to start and give an error message:

Could not build the server_names_hash, you should increase server_names_hash_bucket_size: 32

Therefore, it is better to increase this value to 64. Now you can restart the web server for the changes to take effect:

Sudo service nginx restart

Your server should now be processing requests for both domains.

Step 5 — Setting Up a Local Hosts File (Optional)

If you used your own domain names, then you need to configure your local server so that it recognizes them and you can check your virtual hosts (we will register our domain names in the local host file). Of course, Internet users will not be able to view your site in this way, but it will be enough to check the hosts. This is how we intercept the request to be sent DNS server. In theory, we indicate which ip address our computer should go to when accessing a specific domain name.

Please note that these changes should only be made on the local machine and not on the VPS server. You will need root rights, you also need to have the right to modify system files.

If you are using a Mac or Linux system, then fixes can be made as follows:

sudo nano /etc/hosts

If you use Windows, then you can find instructions for this OS on the official website of the manufacturer (or on google). You need to know the public IP address of your server and the domain names you want to bind to it. Let's say my address is 111.111.111.111 , then I need to add the following lines to the hosts file:

127.0.0.1 localhost 127.0.0.1 guest-desktop 111.111.111.111 example.com 111.111.111.111 test.com

Thus, we will intercept all requests to these domain names and redirect them to our server. Save and close the file when you're done.

Step 6 - Check

On this stage you should get a fully working setup. It remains only to check it. To do this, go to the browser address: http://example.com ( :target="_blank") . If both sites are displayed correctly, then you can be congratulated on full customization nginx server. At this stage, if you made changes to the hosts file, then they should be deleted. The verification was successful and they are no longer needed. To open access to sites for Internet users, you will have to purchase domain names.

Conclusion

You have learned how to fully configure virtual hosts for each site on your server. In fact, there are no restrictions on the number of sites on one machine, except for the resources of the system itself.



Loading...
Top