nginx packages are available for the following Linux distributions and versions:
Version Supported Platforms 7.4+ x86_64, aarch64/arm64 8.x x86_64, aarch64/arm64, s390x 9.x x86_64, aarch64/arm64, s390x
Version Supported Platforms 11.x “bullseye” x86_64, aarch64/arm64
Version Supported Platforms 18.04 “bionic” x86_64, aarch64/arm64 20.04 “focal” x86_64, aarch64/arm64, s390x 22.04 “jammy” x86_64, aarch64/arm64, s390x 22.10 “kinetic” x86_64, aarch64/arm64
Version Supported Platforms 12 SP5+ x86_64 15 SP2+ x86_64
Version Supported platforms 3.14 x86_64, aarch64/arm64 3.15 x86_64, aarch64/arm64 3.16 x86_64, aarch64/arm64 3.17 x86_64, aarch64/arm64
Version Supported platforms 2 (LTS) x86_64, aarch64/arm64
Installation instructions
Before you install nginx for the first time on a new machine, you need to set up the nginx packages repository. Afterward, you can install and update nginx from the repository.
RHEL and derivatives
This section applies to Red Hat Enterprise Linux and its derivatives such as CentOS, Oracle Linux, Rocky Linux, AlmaLinux.
Install the prerequisites:
To set up the yum repository, create the file named /etc/yum.repos.d/nginx.repo with the following contents:
By default, the repository for stable nginx packages is used. If you would like to use mainline nginx packages, run the following command:
To install nginx, run the following command:
When prompted to accept the GPG key, verify that the fingerprint matches 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62 , and if so, accept it.
Debian
Install the prerequisites:
Import an official nginx signing key so apt could verify the packages authenticity. Fetch the key:
Verify that the downloaded file contains the proper key:
The output should contain the full fingerprint 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62 as follows:
If the fingerprint is different, remove the file.
To set up the apt repository for stable nginx packages, run the following command:
If you would like to use mainline nginx packages, run the following command instead:
Set up repository pinning to prefer our packages over distribution-provided ones:
To install nginx, run the following commands:
Ubuntu
Install the prerequisites:
Import an official nginx signing key so apt could verify the packages authenticity. Fetch the key:
Verify that the downloaded file contains the proper key:
The output should contain the full fingerprint 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62 as follows:
If the fingerprint is different, remove the file.
To set up the apt repository for stable nginx packages, run the following command:
If you would like to use mainline nginx packages, run the following command instead:
Set up repository pinning to prefer our packages over distribution-provided ones:
To install nginx, run the following commands:
Install the prerequisites:
To set up the zypper repository for stable nginx packages, run the following command:
If you would like to use mainline nginx packages, run the following command instead:
Next, import an official nginx signing key so zypper/rpm could verify the packages authenticity. Fetch the key:
Verify that the downloaded file contains the proper key:
The output should contain the full fingerprint 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62 as follows:
Finally, import the key to the rpm database:
To install nginx, run the following command:
Alpine
Install the prerequisites:
To set up the apk repository for stable nginx packages, run the following command:
If you would like to use mainline nginx packages, run the following command instead:
Next, import an official nginx signing key so apk could verify the packages authenticity. Fetch the key:
Verify that downloaded file contains the proper key:
The output should contain the following modulus:
Finally, move the key to apk trusted keys storage:
To install nginx, run the following command:
The @nginx tag should also be specified when installing packages with dynamic modules:
Amazon Linux
Install the prerequisites:
To set up the yum repository, create the file named /etc/yum.repos.d/nginx.repo with the following contents:
By default, the repository for stable nginx packages is used. If you would like to use mainline nginx packages, run the following command:
To install nginx, run the following command:
When prompted to accept the GPG key, verify that the fingerprint matches 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62 , and if so, accept it.
Source Packages
Packaging sources can be found in the packaging sources repository.
The default branch holds packaging sources for the current mainline version, while stable-* branches contain latest sources for stable releases. To build binary packages, run make in debian/ directory on Debian/Ubuntu, or in rpm/SPECS/ on RHEL and derivatives, SLES, and Amazon Linux, or in alpine/ on Alpine.
Packaging sources are distributed under the same 2-clause BSD-like license used by nginx.
Dynamic Modules
Main nginx package is built with all modules that do not require additional libraries to avoid extra dependencies. Since version 1.9.11, nginx supports dynamic modules and the following modules are built as dynamic and shipped as separate packages:
Signatures
Since our PGP keys and packages are located on the same server, they are equally trusted. It is highly advised to additionally verify the authenticity of the downloaded PGP key. PGP has the “Web of Trust” concept, when a key is signed by someone else’s key, that in turn is signed by another key and so on. It often makes possible to build a chain from an arbitrary key to someone’s key who you know and trust personally, thus verify the authenticity of the first key in a chain. This concept is described in details in GPG Mini Howto. Our keys have enough signatures, and their authenticity is relatively easy to check.
Как установить nginx на debian
This article explains how to install NGINX Open Source.
Table of Contents
Choosing Between a Stable or a Mainline Version
NGINX Open Source is available in two versions:
- The mainline version. This version includes the latest features and bugfixes and is always up-to-date. It is reliable, but it may include some experimental modules, and it may also have some number of new bugs.
- The stable version. This version doesn’t have new features, but includes critical bug fixes that are always backported to the mainline version. The stable version is recommended for production servers.
Choosing Between a Pre-built Package or Compiling From the Sources
Both NGINX Open Source mainline and stable versions can be installed in two ways:
- from a pre-built package. This is a quick and easy way to install NGINX Open Source. The package includes almost all NGINX official modules and is available for most popular operating systems.
- compiled from the sources. This way is more flexible: you can add particular modules including 3rd party modules or apply latest security patches.
Compiling and Installing From the Sources
Compiling NGINX from the sources provides you with more flexibility: you can add particular NGINX modules or 3rd party modules and apply latest security patches.
Installing NGINX Dependencies
Prior to compiling NGINX from the sources, it is necessary to install its dependencies:
- the PCRE library – required by NGINX Core and Rewrite modules and provides support for regular expressions:
- the zlib library – required by NGINX Gzip module for headers compression:
- the OpenSSL library – required by NGINX SSL modules to support the HTTPS protocol:
Downloading the Sources
NGINX provides source files for both stable and mainline versions. The source files can be downloaded from the NGINX Open Source download page at http://www.nginx.org/en/download.html.
To download and unpack source files for the latest mainline version, type-in the commands:
To download and unpack source files for the latest stable version, type-in the commands:
Configuring the Build Options
Configure options are specified with the ./configure script that sets up various NGINX parameters including paths to source and configuration files, compiler options, connection processing methods and the list of modules. The script ends up with creation of the Makefile required to compile the code and install NGINX.
Example of the configure script:
Configuring NGINX Paths
The configure script allows you to set paths to NIGNX binary and configuration files, and to dependent libraries such as PCRE or SSL in order to link them statically to NGINX binary.
- —prefix=path
defines a directory that will keep NGINX files. The directory will be also used for all relative paths set by the ./configure script (excluding paths to libraries) and for the path to the nginx.conf configuration file.
By default the path is set to /usr/local/nginx . - —sbin-path=path
sets the name of NGINX executable file. This name is used only during installation.
By default the file is named to prefix/sbin/nginx . - —conf-path=path
sets the name of the NGINX configuration file.
By default the file is named prefix/conf/nginx.conf .
Note that regardless of this option you can always start NGINX with a different configuration file by specifying it with the -c option in command-line. - —pid-path=path
sets the name of the nginx.pid file that stores the process ID of the main process. After installation, the path to the file name can always be changed in the nginx.conf configuration file using the pid directive.
By default the file is named prefix/logs/nginx.pid . - —error-log-path=path
sets the name of the primary error, warnings, and diagnostic file. After installation, the file name can always be changed in the nginx.conf configuration file using the error_log directive.
By default the file is named prefix/logs/error.log . - —http-log-path=path
sets the name of the primary request log file of the HTTP server. After installation, the file name can always be changed in the nginx.conf configuration file using the access_log directive.
By default the file is named prefix/logs/access.log . - —user=name
sets the name of an unprivileged user whose credentials will be used by NGINX worker processes. After installation, the name can be changed in the nginx.conf configuration file using the user directive.
The default user name is nobody . - —group=name
sets the name of a group whose credentials will be used by NGINX worker processes. After installation, the name can always be changed in the nginx.conf configuration file using the user directive.
By default, a group name is set to the name of an unprivileged user. - —with-pcre=path
sets the path to the sources of the PCRE library. The library is required for regular expressions support in the location directive and for the ngx_http_rewrite_module module. - —with-pcre-jit
builds the PCRE library with “just-in-time compilation” support (the pcre_jit directive). - —with-zlib=path
sets the path to the sources of the zlib library. The library is required for the ngx_http_gzip_module module.
Configuring NGINX GCC Options
In the configure script you can also specify compiler-related options.
- —with-cc-opt=parameters
sets additional parameters that will be added to the CFLAGS variable.
When using the system PCRE library under FreeBSD, —with-cc-opt=»-I /usr/local/include» must be specified.
If the number of files supported by select() needs to be increased it can also be specified here such as this: —with-cc-opt=»-D FD_SETSIZE=2048″ . - —with-ld-opt=parameters
sets additional parameters that will be used during linking. When using the system PCRE library under FreeBSD, —with-ld-opt=»-L /usr/local/lib» must be specified.
Specifying NGINX Connection Processing Methods
In the configure script you can redefine an event-based polling method. See Connection Processing Methods for details.
- —with-select_module , —without-select_module
enables or disables building a module that allows NGINX to work with the select() method. This module is built automatically if the platform does not appear to support more appropriate methods such as kqueue, epoll, or /dev/poll. - —with-poll_module , —without-poll_module
enables or disables building a module that allows NGINX to work with the poll() method. This module is built automatically if the platform does not appear to support more appropriate methods such as kqueue, epoll, or /dev/poll.
NGINX Modules
NGINX consists of modules. The set of modules as well as other build options are configured with the ./configure script.
Some modules are built by default – they do not require to be specified in the configure script. However, any default module can be excluded from the NGINX binary with the —without- configure option in the configure script.
Modules not included by default as well as third-party modules must be explicitly specified in the configure script together with other build options. Such modules can be linked to NGINX binary either statically and will be loaded each time NGINX starts; or dynamically and will be loaded only if they are specified in the NGINX configuration file.
Modules Built by Default
If you do not need a module built by default, you can disable it by including it to the configure script with the —without- prefix :
| Module Name | Description |
| http_charset_module | Adds the specified charset to the “Content-Type” response header field, can convert data from one charset to another. |
| http_gzip_module | Compresses responses using the gzip method, helping to reduce the size of transmitted data by half or more. |
| http_ssi_module | Processes SSI (Server Side Includes) commands in responses passing through it. |
| http_userid_module | Sets cookies suitable for client identification. |
| http_access_module | Limits access to certain client addresses. |
| http_auth_basic_module | Limits access to resources by validating the user name and password using the HTTP Basic Authentication protocol. |
| http_autoindex_module | Processes requests ending with the slash character (‘/’) and produces a directory listing. |
| http_geo_module | Creates variables with values depending on the client IP address. |
| http_map_module | Creates variables whose values depend on values of other variables. |
| http_split_clients_module | Creates variables suitable for A/B testing, also known as split testing. |
| http_referer_module | Blocks access to a site for requests with invalid values in the Referer header field. |
| http_rewrite_module | Changes the request URI using regular expressions and return redirects; conditionally selects configurations. Requires the PCRE library. |
| http_proxy_module | Passes requests to another server. |
| http_fastcgi_module | Passes requests to a FastCGI server |
| http_uwsgi_module | Passes requests to a uwsgi server. |
| http_scgi_module | Passes requests to an SCGI server. |
| http_memcached_module | Obtains responses from a memcached server. |
| http_limit_conn_module | Limits the number of connections per the defined key, in particular, the number of connections from a single IP address. |
| http_limit_req_module | Limits the request processing rate per a defined key, in particular, the processing rate of requests coming from a single IP address. |
| http_empty_gif_module | Emits single-pixel transparent GIF. |
| http_browser_module | Creates variables whose values depend on the value of the “User-Agent” request header field. |
| http_upstream_hash_module | Enables the hash load balancing method. |
| http_upstream_ip_hash_module | Enables the IP hash load balancing method. |
| http_upstream_least_conn_module | Enables the least_conn load balancing method. |
| http_upstream_keepalive_module | Enables keepalive connections. |
| http_upstream_zone_module | Enables the shared memory zone. |
Modules Not Built by Default
Some NGINX modules are not built by default. You will need to enable them manually by adding to the ./configure command. The mail, stream, geoip, image_filter, perl and xslt modules can be compiled as dynamic. See Dynamic Modules for details.
Example of the ./configure command that includes modules:
- —with-threads
Enables NGINX to use thread pools.
See Thread Pools in NGINX Boost Performance 9x! blog post for details. - —with-file-aio
Enables asynchronous I/O. - —with-ipv6
Enables IPv6 support. - —with-http_ssl_module
Provides support for HTTPS. Requires an SSL library such as OpenSSL.
See the ngx_http_ssl_module reference for the list of directives. - —with-http_v2_module
Provides support for HTTP/2.
See the ngx_http_v2_module reference for the list of directives and the “HTTP/2 Module in NGINX” blog post for details. - —with-http_realip_module
Changes the client address to the one sent in the specified header field.
See the ngx_http_realip_module reference for the list of directives. - —with-http_addition_module
Adds text before and after a response.
See the ngx_http_addition_module reference for the list of directives. - —with-http_xslt_module or —with-http_xslt_module=dynamic
Transforms XML responses using one or more XSLT stylesheets. The module requires the Libxml2 and XSLT libraries.
See the ngx_http_xslt_module reference for the list of directives.
The module can also be compiled as dynamic. - —with-http_image_filter_module or —with-http_image_filter_module=dynamic
Transforms images in JPEG, GIF, and PNG formats. The module requires the LibGD library.
See ngx_http_image_filter_module reference for the list of directives.
The module can also be compiled as dynamic. - —with-http_geoip_module or —with-http_geoip_module=dynamic
Allows creating variables whose values depend on the client IP address. The module uses MaxMind GeoIP databases.
See the ngx_http_geoip_module reference for the list of directives.
The module can also be compiled as dynamic. - —with-http_sub_module
Modifies a response by replacing one specified string by another.
See the ngx_http_sub_module reference for the list of directives. - —with-http_dav_module
Intended for file management automation via the WebDAV protocol.
See the ngx_http_dav_module reference for the list of directives. - —with-http_flv_module
Provides pseudo-streaming server-side support for Flash Video (FLV) files.
See the ngx http_flv_module reference for the list of directives. - —with-mp4_module
Provides pseudo-streaming server-side support for MP4 files.
See the ngx_http_mp4_module reference for the list of directives. - —with-http_gunzip_module
Decompresses responses with Content-Encoding: gzip for clients that do not support zip encoding method.
See the ngx_http_gunzip_module for the list of directives. - —with-http_gzip_static_module
Allows sending precompressed files with the *.gz filename extension instead of regular files.
See the ngx_http_gzip_static_module for the list of directives. - —with-http_auth_request_module
Implements client authorization based on the result of a subrequest.
See the http_auth_request_module for the list of directives. - —with-http_random_index_module
Processes requests ending with the slash character (‘/’) and picks a random file in a directory to serve as an index file.
See the ngx_http_random_index_module for the list of directives. - —with-http_secure_link_module
Used to check authenticity of requested links, protect resources from unauthorized access, and limit link lifetime.
See the ngx_http_secure_link_module for the list of directives. - —with-http_slice_module
Allows splitting a request into subrequests, each subrequest returns a certain range of response. Provides more effective caching of large files.
See the ngx_http_slice_module reference for the list of directives. - —with-http_degradation_module
Allows returning an error when a memory size exceeds the defined value. - —with-http_stub_status_module
Provides access to basic status information.
See the ngx_http_stub_status_module reference for the list of directives.
Note that NGINX Plus customers do not require this module as they are already provided with extended status metrics and interactive dashboard. - —with-http_perl_module or —with-http_perl_module=dynamic
Used to implement location and variable handlers in Perl and insert Perl calls into SSI. Requires the PERL library.
See the ngx_http_perl_module reference for the list of directives.
The module can also be compiled as dynamic. - —with-mail or —with-mail=dynamic
Enables mail proxy functionality.
See the ngx_mail_core_module reference for the list of directives.
The module can also be compiled as dynamic. - —with-mail_ssl_module
Provides support for a mail proxy server to work with the SSL/TLS protocol. Requires an SSL library such as OpenSSL.
See the ngx_mail_ssl_module reference for the list of directives. - —with-stream or —with-stream=dynamic
Enables the TCP proxy functionality.
See the ngx_stream_core_module reference for the list of directives.
The module can also be compiled as dynamic. - —with-stream_ssl_module
Provides support for a stream proxy server to work with the SSL/TLS protocol. Requires an SSL library such as OpenSSL.
See the ngx_stream_ssl_module reference for the list of directives. - —with-google_perftools_module
Allows using Google Performance tools library. - —with-cpp_test_module
- —with-debug
Enables the debugging log.
Third Party Modules
You can extend NGINX functionality by compiling NGINX Open Source with your own module or a third-party module. Some third-party modules are listed in the https://nginx.com/resources/wiki/modules/ page. Use third-party modules at your own risk as their stability is not guaranteed.
Statically Linked Modules
Most modules which are built into NGINX Open Source are statically linked: they are built into NGINX Open Source at compile time and are linked to the NGINX binary statically. These modules can be disabled only after NGINX recompilation.
To compile NGINX Open Source with a statically linked third-party module, in the configure script specify the —add-module= option and type-in the path to the module:
Dynamically Linked Modules
NGINX modules can also be compiled as a shared object (*.so file) and then dynamically loaded into NGINX Open Source at runtime. This provides more flexibility, as the module can be loaded or unloaded at any time with the load_module directive specified in the NGINX configuration file. Note that such a module must support dynamic linking.
To compile NGINX Open Source with a dynamically loaded third-party module, in the configure script specify the —add-dynamic-module= configure option and provide the path to the module:
The resulting *.so files with dynamic modules can be found after compilation in the prefix/modules/ directory, where the prefix is a directory that keep server files, for example, /usr/local/nginx/modules . To load a dynamic module, use the load_module directive after NGINX installation.
Completing the Installation
- Compile and install the build:
- After the installation is finished, run NGINX Open Source:
Installing a Pre-Built Package
Installing NGINX Open Source from a package is much easier and faster comparing to building NGINX from the sources, though it lacks flexibility. Pre-built packages are available for Red Hat, CentOS, Debian, Ubuntu and SLES operating systems.
Modules Included in a Pre-Built Package
See Configure Arguments on nginx.org for the list of modules included in each pre-built package.
Installing Red Hat/CentOS Packages
NGINX provides packages for Red Hat/CentOS 5, 5.x, 6, 6.x, 7 and 7.x. The package can be installed from:
- a default Red Hat or CentOS repository. This is the quickest way, but generally the provided package is outdated. For example, CentOS 7.0 by default offers nginx/1.6.2 released in September, 2014.
- from NGINX repo. You will have to set up the yum repository once, but the provided package will always be up-to-date.
Installing NGINX package From a Default Red Hat/CentOS Repository
- Install the EPEL repository:
- Update the repository and install NGINX Open Source:
- Verify the installation:
Installing From NGINX Repository
- Set up the yum repository for RHEL or CentOS by creating a file nginx.repo in /etc/yum.repos.d, for example, using vi:
- Add the lines to the file:
where:
- “OS” is either rhel or centos
- “OSRELEASE” is the release number: 5, 5.x, 6, 6.x, 7, 7.x
- “/mainline” points to the latest mainline verson. Delete to get the latest stable version
- a default Debian repository. This is the quickest way, but generally the provided package is outdated. For example, Debian 8.2 by default offers nginx/1.6.2 released in September, 2014.
- from NGINX repo. You will have to set up the apt-get repository once, but the provided package will always be up-to-date.
- Update Debian repository information:
- Install the package:
- Verify the installation:
- Download the key used to sign NGINX packages and repository to the apt program keyring and add it:
- Add the “sources” from which NGINX Open Source packages can be obtained: open the /etc/apt/sources.list file in any text editor, for example, vi:
- Add the lines to the file:
where: - codename is a codename of a Debian release:
Version Codename Supported Platforms 7.x wheezy x86_64, i386 8.x jessie x86_64, i386 - “/mainline” points to the latest mainline verson. Delete to get the latest stable version
- a default Ubuntu repository. This is the quickest way, but generally the provided package is outdated. For example, Ubuntu 14.04 by default offers nginx/1.4.6 released in March, 2014.
- NGINX repo. You will have to set up the apt-get repository once, but the provided package will always be up-to-date.
- Update Ubuntu repository information:
- Install the package:
- Verify the installation:
- Download the key used to sign NGINX packages and repository to the apt program keyring and add it:
- Add the “sources” from which NGINX Open Source packages can be obtained: open the /etc/apt/sources.list file in any text editor, for example, vi:
- Add the lines to the file:
where: - codename is a codename of an Ubuntu release:
Version Codename Supported Platforms 12.04 precise x86_64, i386 14.04 trusty x86_64, i386, aarch64/arm64 15.10 wily x86_64, i386 16.04 xenial x86_64, i386 - “/mainline” points to the latest mainline verson. Delete to get the latest stable version
- Nginx Full: открывает порт 80 (незашифрованный сетевой трафик) и 443 (зашифрованный трафик TLS/SSL).
- Nginx HTTP: для незашифрованного трафика HTTP на порт 80.
- Nginx HTTPS: для зашифрованного трафика TLS/SSL на порт 443.
- your_domain : будет обслуживать запросы для www.your_domain и your_domain.
- default будет отвечать на запросы по порту 80, если они не соответствуют остальным виртуальным хостам.
- /var/www/htm: содержит текущий контент сайта. По умолчанию в нём находится только стандартная посадочная страница, которую вы уже видели. Этот каталог можно изменить в конфигурационном файле Nginx.
- /etc/nginx: каталог настроек nginx, в котором хранятся все конфигурационные файлы.
- /etc/nginx/nginx.conf: главный конфигурационный файл Nginx, содержащий глобальные настройки веб-сервера.
- /etc/nginx/sites-available/: каталог, в котором хранятся настроенные блоки server (виртуальные хосты) каждого отдельного сайта. Nginx не будет использовать эти блоки, пока ссылка на них не появится в каталоге sites-enabled (о нём речь пойдёт дальше). Как правило, этот каталог используется для настройки виртуальных хостов.
- /etc/nginx/sites-enabled/: каталог, в котором хранятся включенные блоки server. Чтобы включить блок, нужно создать символьную ссылку на файл, хранящийся в каталоге sites-available.
- /etc/nginx/snippets: этот каталог хранит сниппеты – фрагменты настроек, которые можно включить в конфигурацию Nginx. Как правило, в качестве фрагментов добавляют потенциально повторяемые сегменты конфигурации.
- /var/log/nginx/access.log: регистрирует все запросы, полученные веб-сервером Nginx (если не настроено другое поведение).
- /var/log/nginx/error.log: хранит все сообщения об ошибках Nginx.
Installing Debian Packages
NGINX provides packages for Debian 7.x (“wheezy”) and 8.x (“jessie”). The package can be installed from:
Installing NGINX package From a Default Debian Repository
Installing From NGINX Repository
Installing Ubuntu Packages
NGINX provides packages for Ubuntu 12.04 (“precise”), 14.04 (“trusty”), 15.10 (“wily”) and 16.04 (“xenial”). The package can be installed from:
Installing NGINX package From a Default Ubuntu Repository
Installing From NGINX Repository
Installing SUSE Packages
NGINX provides packages for SUSE Linux Enterprise Server 12.
To download and install the latest stable version, run the commands:
To download and install the latest mainline version, run the commands:
Установка Nginx в Debian
Nginx – это веб сервер с открытым исходным кодом, при помощи которого можно развернуть обратный прокси или веб-сайт. Nginx является вторым (после Apache) по популярности веб-сервером в мире, под управлением которого работают больше 20% всех сайтов и почтовых сервисов.
Главными преимуществами этого сервера являются простота установки и настройки, надёжность, нетребовательность к аппаратным ресурсам и высокая производительность. В этой статье мы рассмотрим как выполняется установка Nginx Debian 11.
Как установить Nginx в Debian
Все команды необходимо выполнять в окне терминала. Запустить его вы сможете либо в меню операционной системы, либо при помощи комбинации клавиш Ctrl+Alt+T. Так выглядит окно терминала в среде рабочего стола XFCE:

Для установки и настройки веб-сервера понадобится доступ к учетной записи пользователя root, убедитесь, что он у вас есть. Для входа под учетной записью суперпользователя воспользуйтесь командой:

Введите пароль root, после чего будет доступна установка и настройка Nginx. Помните, что при вводе пароля в Linux символы не отображаются, не ошибитесь во время ввода. Обновите репозитории и операционную систему, для этого понадобятся команда:
sudo apt update && sudo apt upgrade –y

Установить Nginx можно из официального репозитория Debian, но там доступна устаревшая версия программы. Проверка версии доступной в дистрибутиве выполняется командой:

Для установки Nginx из репозитория Debian введите следующую команду:
sudo apt install nginx
Подтвердите установку Nginx Debian, нажав клавишу y (yes), после чего начнётся скачивание и установка пакетов. Чтобы установить последнюю версию, необходимо добавить репозитории разработчиков Nginx в систему.
1. Добавление репозитория
Для начала установите ключ шифрования GPG от репозиториев Nginx – это нужно, чтобы программа установки могла установить подлинность установочных пакетов:
curl https://nginx.org/keys/nginx_signing.key | gpg —dearmor \| sudo tee /usr/share/keyrings/nginx-archive-keyring.gpg >/dev/null

Убедитесь, что установка ключа шифрования прошла успешно. Для этого выполните следующую команду:
gpg —dry-run —quiet —import —import-options import-show /usr/share/keyrings/nginx-archive-keyring.gpg
Если ключ верный, то должен появится такой вывод в окне терминала:

У Nginx есть две версии репозиториев — mainline (последняя) и stable (стабильная). В стабильной версии не будет самых новых возможностей. Для того чтобы импортировать репозиторий с последней версией выполните:
echo «deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \http://nginx.org/packages/mainline/debian `lsb_release -cs` nginx» | sudo tee /etc/apt/sources.list.d/nginx.list
Если вы хотите добавить репозиторий со стабильной версией — выполните:
echo «deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] \http://nginx.org/packages/debian `lsb_release -cs` nginx» | sudo tee /etc/apt/sources.list.d/nginx.list

Далее нужно выбрать подключенный репозиторий вместо стандартного, это нужно, чтобы установщик пакетов скачал последнюю версию Nginx:
echo -e «Package: *\nPin: origin nginx.org\nPin: release o=nginx\nPin-Priority: 900\n» \| sudo tee /etc/apt/preferences.d/99nginx

2. Установка Nginx из репозитория
После добавления репозиториев необходимо обновить их список, чтобы система приняла изменения:

Теперь запускайте установку Nginx:
apt install nginx -y
Начался процесс скачивания и установки пакетов программы:

Чтобы убедиться в корректности установки и посмотреть версию установленного Nginx, выполните команду:

Можно видеть, что установленная версия из подключенного репозитория Nginx новее, чем из стандартного системного.
3. Запуск и проверка состояния Nginx
Запуск и проверка Nginx производятся при помощи утилиты systemctl. После завершения установки сервер не запущен, запустите его командой:
sudo systemctl start nginx
Сервер запустился, теперь можно посмотреть его состояние:
systemctl status nginx

Пункт active (выделен зелёным) означает успешный запуск сервера. Дополнительно можно посмотреть количество занимаемой памяти (memory), id процесса в оперативной памяти (Main PID).
4. Автозагрузка Nginx
Для автоматического запуска Nginx необходимо снова прибегнуть к помощи утилиты systemctl:
sudo systemctl enable nginx

Для проверки автоматического старта веб-сервера перезагрузите операционную систему, после чего снова проверьте статус Nginx командой status.
5. Проверка работы в браузере
Для проверки работы Nginx нужно зайти на стартовую страницу Nginx в любом браузере. Введите в адресной строке браузера адрес сервера, обычно это 127.0.0.1 или http://localhost. При установке Nginx на удаленный сервер вводите корректный IP-адрес, или правильное доменное имя. Отобразилась такая лаконичная страница, это значит, что сервер запущен и работает правильно:

Выводы
Установка Nginx на Debian 11 – задача несложная, но требующая внимательности при вводе команд, а также при соблюдении последовательности действий. Вы успешно подготовили свой сервер, для дальнейшего использования необходима настройка под ваши конкретные задачи, например, настройка обратного прокси-сервера, почтового сервера.
Регулярно обновляйте Nginx, от этого зависит безопасность вашего сервера. Новые обновления несут в себе исправления ошибок, улучшают общую безопасность системы.
Установка Nginx в Debian 10
Nginx – это один из самых популярных веб-серверов в мире, позволяющий размещать очень большие сайты с высоким трафиком. Он, как правило, расходует меньше ресурсов, чем Apache. Также его можно использовать в качестве обратного прокси-сервера.
Данный мануал поможет установить Nginx на сервер Debian 10.
Требования
Для работы нужен сервер Debian 10, настроенный по этому мануалу.
1: Установка Nginx
Пакет Nginx можно найти в стандартном репозитории Debian.
Поскольку это ваше первое взаимодействие с системой пакетирования apt в текущей сессии, нужно обновить индекс пакетов. После этого можно установить Nginx.
sudo apt update
sudo apt install nginx
Чтобы подтвердить установку, нажмите Enter. После этого пакетный менеджер установит Nginx и все его зависимости.
2: Настройка брандмауэра
Прежде чем запустить Nginx, нужно настроить брандмауэр для поддержки его трафика. Во время установки Nginx регистрирует профиль сервиса в ufw, потому разрешить его трафик очень просто.
Откройте список профилей ufw:
sudo ufw app list
Available applications:
.
Nginx Full
Nginx HTTP
Nginx HTTPS
.
Как видите, в списке зарегистрировано три профиля Nginx:
Рекомендуется выбрать наиболее строгий профиль сервиса. Однако, поскольку на сервере ещё не настроен SSL, мы можем настроить только порт 80.
Чтобы включить профиль, введите:
sudo ufw allow ‘Nginx HTTP’
Убедитесь в том, что профиль включился:
sudo ufw status
Команда должна показать, что трафик HTTP разрешен:
Status: active
To Action From
— —— —-
OpenSSH ALLOW Anywhere
Nginx HTTP ALLOW Anywhere
OpenSSH (v6) ALLOW Anywhere (v6)
Nginx HTTP (v6) ALLOW Anywhere (v6)
3: Тестирование веб-сервера
После установки Debian 10 запустит Nginx автоматически. На данный момент веб-сервер должен работать.
Чтобы убедиться в том, что Nginx запустился, запросите его состояние в системе инициализации systemd.
systemctl status nginx
nginx.service — A high performance web server and a reverse proxy server
Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
Active: active (running) since Wed 2019-07-03 12:52:54 UTC; 4min 23s ago
Docs: man:nginx(8)
Main PID: 3942 (nginx)
Tasks: 3 (limit: 4719)
Memory: 6.1M
CGroup: /system.slice/nginx.service
├─3942 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
├─3943 nginx: worker process
└─3944 nginx: worker process
Как видите, сервис запущен успешно.
Также можно посетить стандартную посадочную страницу Nginx. Она доступна в браузере по домену или IP-адресу.
Если вы не знаете своего IP-адреса, вы можете узнать его с помощью командной строки. Введите:
ip addr show eth0 | grep inet | awk ‘< print $2; >‘ | sed ‘s/\/.*$//’
Команда вернёт несколько строк. Проверьте каждый полученный адрес в браузере.
Узнав свой IP-адрес, введите его в браузер, чтобы убедиться, что веб-сервер работает должным образом.
На экране должна появиться стандартная страница Nginx:
Welcome to nginx!
If you see this page, the nginx web server is successfully installed and working. Further configuration is required.
4: Управление процессами Nginx
Теперь рассмотрим несколько базовых команд для управления веб-сервером.
Чтобы остановить Nginx, введите:
sudo systemctl stop nginx
Чтобы запустить его, введите:
sudo systemctl start nginx
Для перезапуска веб-сервера используйте команду:
sudo systemctl restart nginx
Чтобы обновить настройки Nginx, не сбрасывая соединения, введите команду:
sudo systemctl reload nginx
По умолчанию Nginx автоматически запускается во время загрузки сервера. Это поведение можно выключить:
sudo systemctl disable nginx
Чтобы возобновить автозапуск сервиса, введите:
sudo systemctl enable nginx
5: Настройка виртуального хоста
На веб-сервере Nginx можно использовать виртуальные хосты (также они называются блоками server) для изоляции настроек и размещения нескольких доменов на одном сервере. Здесь используется условный домен example.com, но вы должны заменить его собственным доменом.
В Debian 10 Nginx по умолчанию предоставляет один включенный виртуальный хост, который обслуживает каталог /var/www/html. Этого хватит для обслуживания одного сайта, но если вы хотите разместить несколько сайтов, вам нужно создать новые виртуальные хосты. Создайте структуру каталогов в /var/www для сайта example.com, а /var/www/html оставьте как каталог по умолчанию, который будет обслуживаться, если запрос клиента не соответствует другим сайтам.
Создайте каталог example.com, используя опцию -p для создания всех необходимых родительских каталогов:
sudo mkdir -p /var/www/your_domain/html
Затем установите права на каталог с помощью переменной $USER:
sudo chown -R $USER:$USER /var/www/your_domain/html
Права должны быть установлены правильно, если вы не поменяли unmask, но на всякий случай вы можете их проверить:
sudo chmod -R 755 /var/www/your_domain
Затем создайте образец страницы index.html с помощью nano или другого редактора:
Вставьте в файл:
Сохраните и закройте файл.
Чтобы Nginx смог обслуживать этот контент, необходимо создать файл виртуального хоста с правильным набором директив. Вместо того чтобы напрямую изменять конфигурации по умолчанию, создайте новый файл /etc/nginx/sites-available/example.com.
sudo nano /etc/nginx/sites-available/your_domain
Вставьте следующие конфигурации. Они похожи на конфигурации по умолчанию, но содержат правильный домен и каталог:
server <
listen 80;
listen [::]:80;
root /var/www/your_domain/html;
index index.html index.htm index.nginx-debian.html;
server_name your_domain www.your_domain;
location / <
try_files $uri $uri/ =404;
>
>
Обратите внимание, что root содержит путь к новому каталогу, а server_name – новый домен.
Сохраните и закройте файл.
Включите файл, создав симлинк в каталоге sites-enabled:
sudo ln -s /etc/nginx/sites-available/your_domain /etc/nginx/sites-enabled/
Теперь у вас есть два виртуальных хоста, которые будут обслуживать запросы клиентов на основе директив listen и server_name:
Чтобы избежать потенциальных проблем с памятью, которые могут возникнуть в результате настройки дополнительных имен серверов, необходимо отредактировать одно значение в файле /etc/nginx/nginx.conf. Откройте файл:
sudo nano /etc/nginx/nginx.conf
Найдите строку server_names_hash_bucket_size и раскомментируйте ее, удалив символ #:
Сохраните и закройте файл.
Проверьте ошибки в конфигурационном файле Nginx:
Если ошибок нет, вы увидите такой вывод:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Перезапустите Nginx, чтобы новые параметры вступили в силу:
sudo systemctl restart nginx
Теперь Nginx обслуживает домен вашего сайта. Чтобы убедиться в этом, откройте ссылку http://your_domain в браузере.
Success! The example.com server block is working!
6: Важные файлы и каталоги Nginx
Теперь вы знаете, как управлять сервисом. Пора познакомиться с важными файлами и каталогами веб-сервера Nginx.
Заключение
Теперь веб-сервер Nginx установлен и готов к работе. Используйте его для обслуживания контента вашего сайта. Также теперь вы можете установить более сложный программный стек для поддержки сайта.
