- nginx for Windows
- nginx под Windows
- Configuring HTTPS servers
- HTTPS server optimization
- SSL certificate chains
- A single HTTP/HTTPS server
- Name-based HTTPS servers
- An SSL certificate with several names
- Server Name Indication
- Compatibility
- Как установить и запустить Nginx на Windows 10
- Скачать Nginx:
- Установка и запуск Nginx:
- Nginx запуск на Windows 10:
- Настройка Nginx:
- Переходим на HTTPS на Nginx: шпаргалка
nginx for Windows
Version of nginx for Windows uses the native Win32 API (not the Cygwin emulation layer). Only the select() and poll() (1.15.9) connection processing methods are currently used, so high performance and scalability should not be expected. Due to this and some other known issues version of nginx for Windows is considered to be a beta version. At this time, it provides almost the same functionality as a UNIX version of nginx except for XSLT filter, image filter, GeoIP module, and embedded Perl language.
To install nginx/Windows, download the latest mainline version distribution (1.19.10), since the mainline branch of nginx contains all known fixes. Then unpack the distribution, go to the nginx-1.19.10 directory, and run nginx . Here is an example for the drive C: root directory:
Run the tasklist command-line utility to see nginx processes:
One of the processes is the master process and another is the worker process. If nginx does not start, look for the reason in the error log file logs\error.log . If the log file has not been created, the reason for this should be reported in the Windows Event Log. If an error page is displayed instead of the expected page, also look for the reason in the logs\error.log file.
nginx/Windows uses the directory where it has been run as the prefix for relative paths in the configuration. In the example above, the prefix is C:\nginx-1.19.10\ . Paths in a configuration file must be specified in UNIX-style using forward slashes:
nginx/Windows runs as a standard console application (not a service), and it can be managed using the following commands:
nginx под Windows
Версия nginx под Windows использует “родной” Win32 API (не эмуляцию Cygwin). В настоящий момент в качестве методов обработки соединений используются select() и poll() (1.15.9), поэтому не стоит ожидать высокой производительности и масштабируемости. В силу этого и ряда других известных проблем версия nginx под Windows рассматривается пока как бета-версия. На данный момент в ней доступна практически вся функциональность, что и в версии nginx под UNIX, за исключением XSLT-фильтра, фильтра изображений, модуля GeoIP и встроенного языка Perl.
Чтобы установить nginx/Windows, скачайте дистрибутив последней основной версии (1.19.10), поскольку основная ветвь nginx содержит все известные исправления. Затем распакуйте дистрибутив, перейдите в каталог nginx-1.19.10 и запустите nginx . Вот пример для корневого каталога на диске C:
Чтобы увидеть процессы nginx, запустите утилиту командной строки tasklist :
Один из процессов главный, другой — рабочий. Если nginx не запускается, нужно искать причину в в файле лога ошибок logs\error.log . Если же лог-файл не создался, то причину этого следует искать в Windows Event Log. Если вместо ожидаемой страницы выводится страница с ошибкой, нужно также искать причины ошибки в файле logs\error.log .
nginx/Windows использует каталог, в котором он был запущен, в качестве префикса для относительных путей в конфигурации. В вышеприведённом примере префиксом является C:\nginx-1.19.10\ . Пути в конфигурационном файле должны задаваться в UNIX-стиле с использованием прямых слэшей:
nginx/Windows работает как стандартное консольное приложение (не сервис) и управляется при помощи следующих команд:
Configuring HTTPS servers
To configure an HTTPS server, the ssl parameter must be enabled on listening sockets in the server block, and the locations of the server certificate and private key files should be specified:
The server certificate is a public entity. It is sent to every client that connects to the server. The private key is a secure entity and should be stored in a file with restricted access, however, it must be readable by nginx’s master process. The private key may alternately be stored in the same file as the certificate:
in which case the file access rights should also be restricted. Although the certificate and the key are stored in one file, only the certificate is sent to a client.
The directives ssl_protocols and ssl_ciphers can be used to limit connections to include only the strong versions and ciphers of SSL/TLS. By default nginx uses “ ssl_protocols TLSv1 TLSv1.1 TLSv1.2 ” and “ ssl_ciphers HIGH:!aNULL:!MD5 ”, so configuring them explicitly is generally not needed. Note that default values of these directives were changed several times.
HTTPS server optimization
SSL operations consume extra CPU resources. On multi-processor systems several worker processes should be run, no less than the number of available CPU cores. The most CPU-intensive operation is the SSL handshake. There are two ways to minimize the number of these operations per client: the first is by enabling keepalive connections to send several requests via one connection and the second is to reuse SSL session parameters to avoid SSL handshakes for parallel and subsequent connections. The sessions are stored in an SSL session cache shared between workers and configured by the ssl_session_cache directive. One megabyte of the cache contains about 4000 sessions. The default cache timeout is 5 minutes. It can be increased by using the ssl_session_timeout directive. Here is a sample configuration optimized for a multi-core system with 10 megabyte shared session cache:
SSL certificate chains
Some browsers may complain about a certificate signed by a well-known certificate authority, while other browsers may accept the certificate without issues. This occurs because the issuing authority has signed the server certificate using an intermediate certificate that is not present in the certificate base of well-known trusted certificate authorities which is distributed with a particular browser. In this case the authority provides a bundle of chained certificates which should be concatenated to the signed server certificate. The server certificate must appear before the chained certificates in the combined file:
The resulting file should be used in the ssl_certificate directive:
If the server certificate and the bundle have been concatenated in the wrong order, nginx will fail to start and will display the error message:
because nginx has tried to use the private key with the bundle’s first certificate instead of the server certificate.
Browsers usually store intermediate certificates which they receive and which are signed by trusted authorities, so actively used browsers may already have the required intermediate certificates and may not complain about a certificate sent without a chained bundle. To ensure the server sends the complete certificate chain, the openssl command-line utility may be used, for example:
When testing configurations with SNI, it is important to specify the -servername option as openssl does not use SNI by default.
In this example the subject (“s”) of the www.GoDaddy.com server certificate #0 is signed by an issuer (“i”) which itself is the subject of the certificate #1, which is signed by an issuer which itself is the subject of the certificate #2, which signed by the well-known issuer ValiCert, Inc. whose certificate is stored in the browsers’ built-in certificate base (that lay in the house that Jack built).
If a certificate bundle has not been added, only the server certificate #0 will be shown.
A single HTTP/HTTPS server
It is possible to configure a single server that handles both HTTP and HTTPS requests:
Prior to 0.7.14 SSL could not be enabled selectively for individual listening sockets, as shown above. SSL could only be enabled for the entire server using the ssl directive, making it impossible to set up a single HTTP/HTTPS server. The ssl parameter of the listen directive was added to solve this issue. The use of the ssl directive in modern versions is thus discouraged.
Name-based HTTPS servers
A common issue arises when configuring two or more HTTPS servers listening on a single IP address:
With this configuration a browser receives the default server’s certificate, i.e. www.example.com regardless of the requested server name. This is caused by SSL protocol behaviour. The SSL connection is established before the browser sends an HTTP request and nginx does not know the name of the requested server. Therefore, it may only offer the default server’s certificate.
The oldest and most robust method to resolve the issue is to assign a separate IP address for every HTTPS server:
An SSL certificate with several names
There are other ways that allow sharing a single IP address between several HTTPS servers. However, all of them have their drawbacks. One way is to use a certificate with several names in the SubjectAltName certificate field, for example, www.example.com and www.example.org . However, the SubjectAltName field length is limited.
Another way is to use a certificate with a wildcard name, for example, *.example.org . A wildcard certificate secures all subdomains of the specified domain, but only on one level. This certificate matches www.example.org , but does not match example.org and www.sub.example.org . These two methods can also be combined. A certificate may contain exact and wildcard names in the SubjectAltName field, for example, example.org and *.example.org .
It is better to place a certificate file with several names and its private key file at the http level of configuration to inherit their single memory copy in all servers:
Server Name Indication
A more generic solution for running several HTTPS servers on a single IP address is TLS Server Name Indication extension (SNI, RFC 6066), which allows a browser to pass a requested server name during the SSL handshake and, therefore, the server will know which certificate it should use for the connection. SNI is currently supported by most modern browsers, though may not be used by some old or special clients.
Only domain names can be passed in SNI, however some browsers may erroneously pass an IP address of the server as its name if a request includes literal IP address. One should not rely on this.
In order to use SNI in nginx, it must be supported in both the OpenSSL library with which the nginx binary has been built as well as the library to which it is being dynamically linked at run time. OpenSSL supports SNI since 0.9.8f version if it was built with config option Since OpenSSL 0.9.8j this option is enabled by default. If nginx was built with SNI support, then nginx will show this when run with the “-V” switch:
However, if the SNI-enabled nginx is linked dynamically to an OpenSSL library without SNI support, nginx displays the warning:
Compatibility
- The SNI support status has been shown by the “-V” switch since 0.8.21 and 0.7.62.
- The ssl parameter of the listen directive has been supported since 0.7.14. Prior to 0.8.21 it could only be specified along with the default parameter.
- SNI has been supported since 0.5.23.
- The shared SSL session cache has been supported since 0.5.6.
- Version 1.9.1 and later: the default SSL protocols are TLSv1, TLSv1.1, and TLSv1.2 (if supported by the OpenSSL library).
- Version 0.7.65, 0.8.19 and later: the default SSL protocols are SSLv3, TLSv1, TLSv1.1, and TLSv1.2 (if supported by the OpenSSL library).
- Version 0.7.64, 0.8.18 and earlier: the default SSL protocols are SSLv2, SSLv3, and TLSv1.
- Version 1.0.5 and later: the default SSL ciphers are “ HIGH:!aNULL:!MD5 ”.
- Version 0.7.65, 0.8.20 and later: the default SSL ciphers are “ HIGH:!ADH:!MD5 ”.
- Version 0.8.19: the default SSL ciphers are “ ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM ”.
- Version 0.7.64, 0.8.18 and earlier: the default SSL ciphers are
“ ALL:!ADH:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP ”.
Как установить и запустить Nginx на Windows 10
В этой статье мы разберём, как установить Nginx на Windows 10 и запустить его, также эта инструкция подойдёт для Windows 7 и Windows 8.
Ещё перед этой статьи, прочитаете «Как установить Apache на Windows»,это если вам нужен будет Apache.
Скачать Nginx:
Перед тем как установить, нужно скачать Nginx, переходите по этой ссылки, там скачаете архив с ним.
Как видите я скачал стабильную версию, и вам тоже рекомендую так именно её, так как, основной могут быть баги.
После того как скачали, открываем архив и папку внутри, перемешаем в папку которую вам надо, но я рекомендую в «Program Files», иначе придётся ещё добавлять Nginx в директиву «path».
Установка и запуск Nginx:
После того, как вы переместили, заходите в папку и Nginx и запускаем файл «nginx.exe», по двойному клику левой кнопки мыши.
Тут стоит сказать, что при установки у вас не чего не появится и это может смутить, но чтобы убедится, видите в адресную строку браузера «http://localhost/», должно появится вот это.
Если у вас именно это, то значит всё работает так как надо.
Nginx запуск на Windows 10:
Единственное что стоит сказать, при перезагрузки компьютера или выключение и включение, сервер перестают работает, чтобы это исправить, есть два способа, первый через встроенный Windows server, но его я не буду, так как, он достаточно сложный и на мой взгляд не очень удобный, второй, это просто отправить на рабочий стол, в качестве ярлыка файл «nginx.exe».
Теперь вы можете спокойно запускать его с рабочего стола.
Настройка Nginx:
Последние что стоит рассказать, это то, как его настроить что бы было ещё удобрение, для этого заходим в папку со сервером и там переходим в «conf», и открываем файл «nginx.conf».
Единственное, что стоит в нём изменить, это грубо говоря массив «location», который указывает настройки для стартовой страницы сервера, надо изменить значение у ключа «root», в качестве значения используете путь до папки с вашим сайтом.
Переходим на HTTPS на Nginx: шпаргалка
Уже второй раз сталкиваюсь с задачей «поставь https на наш сервер» от моего босса, поэтому решил сделать для самого себя шпаргалку, а заодно и для всех остальных. Итак, ситуация следующая: к нам пришел босс и заявил, что ему нужен https. Под катом я напишу 5 простых шагов, как все сделать буквально за час. Приступим.
0. Отправляем босса покупать нам доменное имя, если его у нас еще нет — без доменного имени https поставить нельзя. После покупки не забываем прописать NS-записи в панели управления нашего сервера, а также A-запись.
1. Отправляем босса за SSL-сертификатом на nic.ru и пускай он там покупает себе thawte 123 сертификат, а мы тем временем сгенерируем для него CSR-запрос.
2. Заходим по SSH на сервер и далее пишем:
3. Создаем CSR-запрос вот этой строкой: , причем информацию (типа company name, email) берем через сервис whois (зачем еще раз спрашивать все у босса, когда можно все узнать самостоятельно).
4. В это время босс дошел до той стадии, когда ему потребуется только что созданный нами CSR-запрос. Мы говорим ему, чтобы он залез по SSH на сервер и командой скопировал код и вставил его куда нужно.
5. Затем босс попросит нас подтвердить владение доменом через создание почты типа admin@our-domain.com. Для этого мы воспользуемся сервисом «почта для доменов» от «Яндекса». Создаем там почту и сообщаем боссу логин/пароль.
6. Создаем bundled PEM-сертификат. Босс должен будет переслать письмо от thawte, в котором в PEM-формате будет лежать наш сертификат. Мы должны открыть sublime text и вставить туда этот сертификат, а также скачать промежуточный сертификат с сайта thawte, вставить его в тот же файл и сохранить в /etc/nginx/certificate_bundled.crt. Внимание! Сначала идет то, что нам выслал босс, а уже потом — промежуточный сертификат, который мы скачали по той ссылке.
7. Копируем приватный ключ туда же командой
8. Открываем конфиг /etc/nginx/nginx.conf и настраиваем согласно инструкциям в публикации «Настраиваем HTTPS-сервер на nginx». Если вкратце, нам надо в /etc/nginx/nginx.conf в секцию http прописать
Затем в /etc/nginx/conf.d/example_ssl.conf в секции server:
9. Отключаем пароль для приватного ключа командой:
10. Перезагружаем nginx командой и — вуаля!