- nginx под Windows
- nginx: пакеты для Linux
- Поддерживаемые дистрибутивы и версии
- Инструкции по установке
- RHEL/CentOS
- Debian
- Ubuntu
- Alpine
- Amazon Linux
- Пакеты с исходным кодом
- Динамические модули
- Подписи
- Installing NGINX Open Source
- Choosing Between a Stable or a Mainline Version
- Choosing Between a Prebuilt Package and Compiling from Source
- Installing a Prebuilt Package
- Modules Included in a Prebuilt Package
- Installing Prebuilt CentOS and RHEL Packages
- Installing a Prebuilt CentOS/RHEL Package from an OS Repository
- Installing a Prebuilt CentOS/RHEL Package from the Official NGINX Repository
- Installing Prebuilt Debian Packages
- Installing a Prebuilt Debian Package from an OS Repository
- Installing a Prebuilt Debian Package from the Official NGINX Repository
- Installing Prebuilt Ubuntu Packages
- Installing a Prebuilt Ubuntu Package from an Ubuntu Repository
- Installing a Prebuilt Ubuntu Package from the Official NGINX Repository
- Installing SUSE Packages
- Installing Prebuilt Alpine Linux Packages
- Installing a Prebuilt Alpine Linux Package from the Official NGINX Repository
- Compiling and Installing from Source
- Installing NGINX Dependencies
- Downloading the Sources
- Configuring the Build Options
- Configuring NGINX Paths
- Including Modules Not Built by Default
nginx под Windows
Версия nginx под Windows использует “родной” Win32 API (не эмуляцию Cygwin). В настоящий момент в качестве методов обработки соединений используются select() и poll() (1.15.9), поэтому не стоит ожидать высокой производительности и масштабируемости. В силу этого и ряда других известных проблем версия nginx под Windows рассматривается пока как бета-версия. На данный момент в ней доступна практически вся функциональность, что и в версии nginx под UNIX, за исключением XSLT-фильтра, фильтра изображений, модуля GeoIP и встроенного языка Perl.
Чтобы установить nginx/Windows, скачайте дистрибутив последней основной версии (1.21.3), поскольку основная ветвь nginx содержит все известные исправления. Затем распакуйте дистрибутив, перейдите в каталог nginx-1.21.3 и запустите nginx . Вот пример для корневого каталога на диске C:
Чтобы увидеть процессы nginx, запустите утилиту командной строки tasklist :
Один из процессов главный, другой — рабочий. Если nginx не запускается, нужно искать причину в в файле лога ошибок logs\error.log . Если же лог-файл не создался, то причину этого следует искать в Windows Event Log. Если вместо ожидаемой страницы выводится страница с ошибкой, нужно также искать причины ошибки в файле logs\error.log .
nginx/Windows использует каталог, в котором он был запущен, в качестве префикса для относительных путей в конфигурации. В вышеприведённом примере префиксом является C:\nginx-1.21.3\ . Пути в конфигурационном файле должны задаваться в UNIX-стиле с использованием прямых слэшей:
nginx/Windows работает как стандартное консольное приложение (не сервис) и управляется при помощи следующих команд:
Источник
nginx: пакеты для Linux
Поддерживаемые дистрибутивы и версии
Пакеты nginx доступны для следующих дистрибутивов Linux и их версий:
Версия Поддерживаемые платформы 7.4+ x86_64, ppc64le, aarch64/arm64 8.x x86_64, aarch64/arm64
Версия Поддерживаемые платформы 10.x “buster” x86_64, i386, aarch64/arm64 11.x “bullseye” x86_64, aarch64/arm64
Версия Поддерживаемые платформы 18.04 “bionic” x86_64, aarch64/arm64 20.04 “focal” x86_64, aarch64/arm64 21.04 “hirsute” x86_64, aarch64/arm64
Версия Поддерживаемые платформы 12 SP5+ x86_64 15 SP2+ x86_64
Версия Поддерживаемые платформы 3.11 x86_64 3.12 x86_64, aarch64/arm64 3.13 x86_64, aarch64/arm64 3.14 x86_64, aarch64/arm64
Версия Поддерживаемые платформы 2 (LTS) x86_64, aarch64/arm64
Инструкции по установке
Для того, чтобы поставить nginx на новой машине, необходимо подключить и настроить репозиторий пакетов nginx. После этого можно будет установить и обновлять nginx из этого репозитория.
RHEL/CentOS
Установите пакеты, необходимые для подключения yum-репозитория:
Для подключения yum-репозитория создайте файл с именем /etc/yum.repos.d/nginx.repo со следующим содержимым:
По умолчанию используется репозиторий для стабильной версии nginx. Если предпочтительно использовать пакеты для основной версии nginx, выполните следующую команду:
Чтобы установить nginx, выполните следующую команду:
При запросе подтверждения GPG-ключа проверьте, что отпечаток ключа совпадает с 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62 , и, если это так, подтвердите его.
Debian
Установите пакеты, необходимые для подключения apt-репозитория:
Теперь нужно импортировать официальный ключ, используемый apt для проверки подлинности пакетов. Скачайте ключ:
Проверьте, верный ли ключ был загружен:
Вывод команды должен содержать полный отпечаток ключа 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62 :
Если отпечаток отличается от вышеуказанного, удалите файл ключа.
Для подключения apt-репозитория для стабильной версии nginx, выполните следующую команду:
Если предпочтительно использовать пакеты для основной версии nginx, выполните следующую команду вместо предыдущей:
Для использования пакетов из нашего репозитория вместо распространяемых в дистрибутиве, настройте закрепление:
Чтобы установить nginx, выполните следующие команды:
Ubuntu
Установите пакеты, необходимые для подключения apt-репозитория:
Теперь нужно импортировать официальный ключ, используемый apt для проверки подлинности пакетов. Скачайте ключ:
Проверьте, верный ли ключ был загружен:
Вывод команды должен содержать полный отпечаток ключа 573BFD6B3D8FBC641079A6ABABF5BD827BD9BF62 :
Если отпечаток отличается от вышеуказанного, удалите файл ключа.
Для подключения apt-репозитория для стабильной версии nginx, выполните следующую команду:
Если предпочтительно использовать пакеты для основной версии nginx, выполните следующую команду вместо предыдущей:
Для использования пакетов из нашего репозитория вместо распространяемых в дистрибутиве, настройте закрепление:
Чтобы установить nginx, выполните следующие команды:
Установите пакеты, необходимые для подключения zypper-репозитория:
Для подключения zypper-репозитория для стабильной версии nginx, выполните следующую команду:
Если предпочтительно использовать пакеты для основной версии nginx, выполните следующую команду вместо предыдущей:
Теперь нужно импортировать официальный ключ, используемый zypper/rpm для проверки подлинности пакетов. Скачайте ключ:
Проверьте, верный ли ключ был загружен:
Вывод команды должен содержать полный отпечаток ключа 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62 :
Импортируйте ключ в базу данных rpm:
Чтобы установить nginx, выполните следующую команду:
Alpine
Установите пакеты, необходимые для подключения apk-репозитория:
Для подключения apk-репозитория для стабильной версии nginx, выполните следующую команду:
Если предпочтительно использовать пакеты для основной версии nginx, выполните следующую команду вместо предыдущей:
Теперь нужно импортировать официальный ключ, используемый apk для проверки подлинности пакетов. Скачайте ключ:
Проверьте, верный ли ключ был загружен:
Вывод команды должен содержать следующий модуль:
Переместите ключ в каталог доверенных ключей apk:
Чтобы установить nginx, выполните следующую команду:
Тэг @nginx должен быть указан и при установке пакетов с динамическими модулями:
Amazon Linux
Установите пакеты, необходимые для подключения yum-репозитория:
Для подключения yum-репозитория создайте файл с именем /etc/yum.repos.d/nginx.repo со следующим содержимым:
По умолчанию используется репозиторий для стабильной версии nginx. Если предпочтительно использовать пакеты для основной версии nginx, выполните следующую команду:
Чтобы установить nginx, выполните следующую команду:
При запросе подтверждения GPG-ключа проверьте, что отпечаток ключа совпадает с 573B FD6B 3D8F BC64 1079 A6AB ABF5 BD82 7BD9 BF62 , и, если это так, подтвердите его.
Пакеты с исходным кодом
Исходные коды пакетов находятся в соответствующем репозитории.
Ветка репозитория default содержит исходные коды пакетов для mainline-версии, в то время как ветки stable-* содержат исходные коды пакетов для стабильных релизов. Для сборки бинарных пакетов запустите make в каталоге debian/ для Debian/Ubuntu, или в каталоге rpm/SPECS/ для RHEL/CentOS/SLES/Amazon Linux, или в каталоге alpine/ для Alpine.
Исходные коды пакетов распространяются под той же BSD-подобной лицензией из 2 пунктов, что и сам nginx.
Динамические модули
Для того чтобы избежать увеличения числа зависимостей, основной пакет nginx не включает модули, которым требуются дополнительные библиотеки. Начиная с версии 1.9.11 nginx поддерживает динамические модули, и следующие модули собираются как динамические и поставляются в виде отдельных пакетов:
Подписи
Поскольку наши PGP-ключи находятся на том же сервере, что и пакеты, им следует доверять в равной степени. Поэтому мы настоятельно рекомендуем дополнительно проверить подлинность загруженных PGP-ключей. В PGP есть понятие “сети доверия”, когда ключ подписывается чьим-либо другим ключом, тот в свою очередь третьим, и т.д. Это зачастую позволяет построить цепочку от произвольного ключа до ключа человека, которого вы знаете и кому доверяете лично, и таким образом удостовериться в подлинности первого ключа в цепочке. Подробно эта концепция описана в GPG Mini Howto. У наших ключей есть достаточное количество подписей, поэтому проверить их подлинность относительно несложно.
Источник
Installing NGINX Open Source
Install NGINX Open Source either as a prebuilt package or from source, following step-by-step instructions for all supported Linux distributions.
This article explains how to install NGINX Open Source.
Choosing Between a Stable or a Mainline Version
NGINX Open Source is available in two versions:
- Mainline – Includes the latest features and bug fixes 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.
- Stable – Doesn’t include all of the latest features, but has critical bug fixes that are always backported to the mainline version. We recommend the stable version for production servers.
Choosing Between a Prebuilt Package and Compiling from Source
Both the NGINX Open Source mainline and stable versions can be installed in two ways:
- As a prebuilt binary package. This is a quick and easy way to install NGINX Open Source. The package includes almost all official NGINX modules and is available for most popular operating systems. See Installing a Prebuilt Package.
- As binaries you compile from source. This way is more flexible: you can add particular modules, including third‑party modules, or apply the latest security patches. See Compiling and Installing from Source for details.
Installing a Prebuilt Package
Installing NGINX Open Source from a package is much easier and faster than building from source, but building from source enables you to compile in non-standard modules. Prebuilt packages are available for most popular Linux distributions, including CentOS, Debian, Red Hat Enterprise Linux (RHEL), SUSE Linux Enterprise Server (SLES), and Ubuntu. See Linux packages at nginx.org for the list of currently supported operating systems.
Modules Included in a Prebuilt Package
See Configure Arguments at nginx.org for the list of modules included in each prebuilt package.
Installing Prebuilt CentOS and RHEL Packages
NGINX, Inc. provides packages for the following CentOS, Oracle Linux, and RHEL versions:
Version | Supported Platforms |
---|---|
6.x | x86_64, i386 |
7.4+ | x86_64, ppc64le |
8.x | x86_64 |
The package can be installed from:
- A default RHEL or CentOS repository. This is the quickest way, but generally the provided package is outdated.
- The official repo at nginx.org. You have to set up the yum repository the first time, but after that the provided package is always up to date.
Installing a Prebuilt CentOS/RHEL Package from an OS Repository
Install the EPEL repository:
Update the repository:
Install NGINX Open Source:
Verify the installation:
Installing a Prebuilt CentOS/RHEL Package from the Official NGINX Repository
Set up the yum repository for RHEL or CentOS by creating the file nginx.repo in /etc/yum.repos.d, for example using vi :
Add the following lines to nginx.repo:
The /mainline element in the pathname points to the latest mainline version of NGINX Open Source; delete it to get the latest stable version
is either rhel or centos
is the release number ( 6 , 6._x_ , 7 , 7._x_ and so on)
For example, to get the latest mainline package for CentOS 7, insert:
Save the changes and quit vi (press ESC and type wq at the : prompt).
Update the repository:
Install the NGINX Open Source package:
Start NGINX Open Source:
Verify that NGINX Open Source is up and running:
Installing Prebuilt Debian Packages
NGINX provides packages for the following Debian operating systems:
Version | Codename | Supported Platforms |
---|---|---|
9.x | stretch | x86_64, i386 |
10.x | buster | x86_64, i386 |
The package can be installed from:
- A default Debian repository. This is the quickest way, but generally the provided package is outdated.
- The official repo at nginx.org. You have to set up the apt-get repository the first time, but after that the provided package is always up to date.
Installing a Prebuilt Debian Package from an OS Repository
Update the Debian repository information:
Install the NGINX Open Source package:
Verify the installation:
Installing a Prebuilt Debian Package from the Official NGINX Repository
Download the key used to sign NGINX packages and the repository, and add it to the apt program’s key ring:
Edit the /etc/apt/sources.list file, for example with vi :
Add these lines to sources.list to name the repositories from which the NGINX Open Source can be obtained:
The /mainline element in the pathname points to the latest mainline version of NGINX Open Source; delete it to get the latest stable version
is the codename of a Debian release
For example, to get the latest mainline package for Debian 8.2 (“jessie”), insert:
Save the changes and quit vi (press ESC and type wq at the : prompt).
Install the NGINX package:
Start NGINX Open Source:
Verify that NGINX Open Source is up and running:
Installing Prebuilt Ubuntu Packages
NGINX provides packages for the following Ubuntu operating systems:
Version | Codename | Supported Platforms |
---|---|---|
16.04 | xenial | x86_64, i386, ppc64el, aarch64/arm64 |
18.04 | bionic | x86_64, aarch64/arm64 |
19.10 | eoan | x86_64 |
20.04 | focal | x86_64, aarch64/arm64 |
The package can be installed from:
- A default Ubuntu repository. This is the quickest way, but generally the provided package is outdated.
- The official repo at nginx.org. You have to set up the apt-get repository the first time, but after that the provided package is always up to date.
Installing a Prebuilt Ubuntu Package from an Ubuntu Repository
Update the Ubuntu repository information:
Install the package:
Verify the installation:
Installing a Prebuilt Ubuntu Package from the Official NGINX Repository
Download the key used to sign NGINX packages and the repository, and add it to the apt program’s key ring:
Edit the /etc/apt/sources.list file, for example with vi :
Add these lines sources.list to name the repositories from which the NGINX Open Source source can be obtained:
- The /mainline element in the pathname points to the latest mainline version of NGINX Open Source; delete it to get the latest stable version
- is the codename of an Ubuntu release
For example, to get the latest mainline package for Ubuntu 14.04 (“trusty”), add:
Save the changes and quit vi (press ESC and type wq at the : prompt).
Install NGINX Open Source:
Start NGINX Open Source:
Verify that NGINX Open Source is up and running:
Installing SUSE Packages
NGINX provides packages for SUSE Linux Enterprise Server:
Version | Supported Platforms |
---|---|
SLES 12 | x86_64 |
SLES 15 | x86_64 |
To download and install the latest stable version for SLES 12, run:
To download and install the latest mainline version for SLES 12, run:
Installing Prebuilt Alpine Linux Packages
NGINX provides packages for the following Alpine Linux operating systems:
Version | Supported Platforms |
---|---|
3.8 | x86_64 |
3.9 | x86_64 |
3.10 | x86_64 |
3.11 | x86_64 |
The package can be installed from the official repo at nginx.org. You have to set up the apt-get repository the first time, but after that the provided package is always up to date.
Installing a Prebuilt Alpine Linux Package from the Official NGINX Repository
Install the prerequisites:
To set up the apk repository for stable nginx packages, run the command:
For mainline nginx packages, run the following command instead:
Import an official nginx signing key so apk could verify the packages authenticity. Fetch the key:
Verify that the downloaded file contains the proper key:
The output should contain the following modulus:
Move the key to apk trusted keys storage:
To install nginx, run the command:
Compiling and Installing from Source
Compiling NGINX Open Source from source affords more flexibility than prebuilt packages: you can add particular modules (from NGINX or third parties), and apply latest security patches.
Installing NGINX Dependencies
Prior to compiling NGINX Open Source from source, you need to install libraries for its dependencies:
PCRE – Supports regular expressions. Required by the NGINX Core and Rewrite modules.
zlib – Supports header compression. Required by the NGINX Gzip module.
OpenSSL – Supports the HTTPS protocol. Required by the NGINX SSL module and others.
Downloading the Sources
Download the source files for both the stable and mainline versions from nginx.org.
To download and unpack the source for the latest mainline version, run:
To download and unpack source files for the latest stable version, run:
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 finishes by creating the Makefile required to compile the code and install NGINX Open Source.
An example of options to the configure script (should be typed as a single line):
Configuring NGINX Paths
The configure script allows you to set paths to NGINX binary and configuration files, and to dependent libraries such as PCRE or SSL, in order to link them statically to the NGINX binary.
Parameter | Description |
---|---|
—prefix= |
Module Name | Description |
---|---|
http_access_module | Accepts or denies requests from specified 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 forward-slash character (/) and produces a directory listing. |
http_browser_module | Creates variables whose values depend on the value of the User-Agent request header. |
http_charset_module | Adds the specified character set to the Content-Type response header. Can convert data from one character set to another. |
http_empty_gif_module | Emits a single-pixel transparent GIF. |
http_fastcgi_module | Passes requests to a FastCGI server. |
http_geo_module | Creates variables with values that depend on the client IP address. |
http_gzip_module | Compresses responses using gzip , reducing the amount of transmitted data by half or more. |
http_limit_conn_module | Limits the number of connections per a 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_map_module | Creates variables whose values depend on the values of other variables. |
http_memcached_module | Passes requests to a memcached server. |
http_proxy_module | Passes HTTP requests to another server. |
http_referer_module | Blocks requests with invalid values in the Referer header. |
http_rewrite_module | Changes the request URI using regular expressions and return redirects; conditionally selects configurations. Requires the PCRE library. |
http_scgi_module | Passes requests to an SCGI server. |
http_ssi_module | Processes SSI (Server Side Includes) commands in responses passing through it. |
http_split_clients_module | Creates variables suitable for A/B testing, also known as split testing. |
http_upstream_hash_module | Enables the generic Hash load-balancing method. |
http_upstream_ip_hash_module | Enables the IP Hash load-balancing method. |
http_upstream_keepalive_module | Enables keepalive connections. |
http_upstream_least_conn_module | Enables the Least Connections load-balancing method. |
http_upstream_zone_module | Enables shared memory zones. |
http_userid_module | Sets cookies suitable for client identification. |
http_uwsgi_module | Passes requests to a uwsgi server. |
Including Modules Not Built by Default
Many NGINX modules are not built by default, and must be listed on the configure command line to be built.
The mail, stream, geoip, image_filter, perl and xslt modules can be compiled as dynamic. See Dynamic Modules for details.
An example of the configure command that includes nondefault modules (should be typed as a single line):
-
- —with-cpp_test_module
- Tests the C++ compatibility of header files.
-
- —with-debug
- Enables the debugging log.
-
-
Enables asynchronous I/O.
-
-
- — with-http_addition_module
- Adds text before and after a response.
-
- — with-http_auth_request_module
- Implements client authorization based on the result of a subrequest.
-
- — with-http_dav_module
- Enables file management automation using the WebDAV protocol.
-
- —with-http_degradation_module
- Allows returning an error when a memory size exceeds the defined value.
-
- — with-http_flv_module
- Provides pseudo-streaming server-side support for Flash Video (FLV) files.
-
- — with-http_geoip_module
- Enables creating variables whose values depend on the client IP address. The module uses MaxMind GeoIP databases. To compile as a separate dynamic module instead, change the option to —with-http_geoip_module=dynamic .
-
- — with-http_gunzip_module
- Decompresses responses with Content-Encoding: gzip for clients that do not support the zip encoding method.
-
- — with-http_gzip_static_module
- Allows sending precompressed files with the .gz filename extension instead of regular files.
-
- — with-http_image_filter_module
- Transforms images in JPEG, GIF, and PNG formats. The module requires the LibGD library. To compile as a separate dynamic module instead, change the option to —with-http_image_filter_module=dynamic .
-
- — with-http_mp4_module
- Provides pseudo-streaming server-side support for MP4 files.
-
- — with-http_perl_module
- Used to implement location and variable handlers in Perl and insert Perl calls into SSI. Requires the PERL library. To compile as a separate dynamic module instead, change the option to —with-http_perl_module=dynamic .
-
- — 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.
-
- — with-http_realip_module
- Changes the client address to the one sent in the specified header field.
-
- — with-http_secure_link_module
- Used to check authenticity of requested links, protect resources from unauthorized access, and limit link lifetime.
-
- — 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.
-
- — with-http_ssl_module
- Enables HTTPS support. Requires an SSL library such as OpenSSL.
-
- — with-http_stub_status_module
- Provides access to basic status information. Note that NGINX Plus customers do not require this module as they are already provided with extended status metrics and interactive dashboard.
-
- — with-http_sub_module
- Modifies a response by replacing one specified string by another.
-
- — with-http_xslt_module
- Transforms XML responses using one or more XSLT stylesheets. The module requires the Libxml2 and XSLT libraries. To compile as a separate dynamic module instead, change the option to —with-http_xslt_module=dynamic .
-
- — with-http_v2_module
- Enable support for HTTP/2). See The HTTP/2 Module in NGINX on the NGINX blog for details.
-
- — with-mail
- Enables mail proxy functionality. To compile as a separate dynamic module instead, change the option to —with-mail=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.
-
- — with-stream
- Enables the TCP and UDP proxy functionality. To compile as a separate dynamic module instead, change the option to —with-stream=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.
-
- —with-threads
- Enables NGINX to use thread pools. For details, see Thread Pools in NGINX Boost Performance 9x! on the NGINX blog.
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 by adding or removing the associated load_module directive in the NGINX configuration file and reloading the configuration. Note that the module itself must support dynamic linking.
To compile NGINX Open Source with a dynamically loaded third‑party module, include the —add-dynamic-module=
option on the configure command, where
is the path to the source code:
The resulting *.so files are written to the prefix/modules/ directory, where the prefix is a directory for server files such as /usr/local/nginx/.
To load a dynamic module, add the load_module directive to the NGINX configuration after installation:
Источник