Как настроить nginx на windows

Версия nginx под Windows использует “родной” Win32 API (не эмуляцию Cygwin).
В настоящий момент в качестве методов обработки соединений используются
select() и poll() (1.15.9),
поэтому не стоит ожидать высокой производительности и масштабируемости.
В силу этого и ряда других известных проблем версия nginx под Windows
рассматривается пока как бета-версия.
На данный момент в ней доступна практически вся функциональность, что и
в версии nginx под UNIX, за исключением
XSLT-фильтра, фильтра изображений, модуля GeoIP и встроенного языка Perl.

Чтобы установить nginx/Windows, скачайте
дистрибутив последней основной версии (1.25.2),
поскольку основная ветвь nginx содержит все известные исправления.
Затем распакуйте дистрибутив, перейдите в каталог
nginx-1.25.2
и запустите nginx.
Вот пример для корневого каталога на диске C:

cd c:\
unzip nginx-1.25.2.zip
cd nginx-1.25.2
start nginx

Чтобы увидеть процессы nginx, запустите утилиту командной строки
tasklist:

C:\nginx-1.25.2>tasklist /fi "imagename eq nginx.exe"

Image Name           PID Session Name     Session#    Mem Usage
=============== ======== ============== ========== ============
nginx.exe            652 Console                 0      2 780 K
nginx.exe           1332 Console                 0      3 112 K

Один из процессов главный, другой — рабочий.
Если nginx не запускается, нужно искать причину в
в файле лога ошибок logs\error.log.
Если же лог-файл не создался, то причину этого следует искать
в Windows Event Log.
Если вместо ожидаемой страницы выводится страница с ошибкой, нужно также
искать причины ошибки в файле logs\error.log.

nginx/Windows использует каталог, в котором он был запущен, в качестве
префикса для относительных путей в конфигурации.
В вышеприведённом примере префиксом является
C:\nginx-1.25.2\.
Пути в конфигурационном файле должны задаваться в UNIX-стиле с использованием
прямых слэшей:

access_log   logs/site.log;
root         C:/web/html;

nginx/Windows работает как стандартное консольное приложение (не сервис)
и управляется при помощи следующих команд:

nginx -s stop быстрое завершение
nginx -s quit плавное завершение
nginx -s reload изменение конфигурации,
запуск новых рабочих процессов с новой конфигурацией,
плавное завершение старых рабочих процессов
nginx -s reopen переоткрытие лог-файлов

Известные проблемы

  • Хоть и возможен запуск нескольких рабочих процессов, только один из них
    реально работает.
  • Проксирование по UDP не поддерживается.

Возможные усовершенствования в будущем

  • Запуск в виде сервиса.
  • Использование портов завершения ввода-вывода (I/O completion ports)
    в качестве метода обработки соединений.
  • Использование нескольких рабочих нитей внутри одного рабочего процесса.

Как установить и запустить сервер Nginx на Windows 10

Nginx — это веб-сервер, который очень популярен в Linux и BSD системах. Многие полагают, что установить Nginx на Windows 10 невозможно. Это совсем не так.

Согласно информации, размещенной на сайте Nginx, установка на Windows 10 возможна, но есть несколько ограничений производительности, которые пока не были устранены. К ним относятся только одно рабочее веб-приложение, отсутствие масштабируемости и возможные проблемы с UDP аутентификацией. На данный момент Nginx уже упоминал, что он решит все проблемы в своих будущих выпусках.

Чтобы успешно установить и запустить Nginx на Windows 10, выполните следующие действия.

Загрузите Nginx Server

Существует много загружаемых версий Nginx для Windows, но Nginx рекомендует использовать “mainline version”. Однако, вы не найдете никаких проблем, если загрузите последнюю стабильную версию этой программы.

Выберите последний ZIP-файл и загрузите его в новую папку.

Как установить и запустить сервер Nginx на Windows 10 1

В качестве первого шага необходимо распаковать его. Вы можете использовать 7-Zip, WinRAR или любое другое популярное программное обеспечение для архивации.

Как установить и запустить сервер Nginx на Windows 10 2

После извлечения содержимого архива из первоначальной директории необходимо переместить папку, которая поставлялась со встроенной загрузочной копией. в «Program Files».

Как установить и запустить сервер Nginx на Windows 10 3

Мы запустим Nginx из этого места в качестве веб-сервиса по умолчанию.

Как установить и запустить сервер Nginx на Windows 10 4

Чтобы установить и запустить Nginx, выберите и дважды щелкните файл Nginx.exe.

Как установить и запустить сервер Nginx на Windows 10 5

На следующем шаге вам нужно проверить, была ли установка успешной. Для этого вы можете перейти в браузер по умолчанию и ввести “localhost”. Если вы увидите следующее окно с сообщением об успешной установке и работе веб-сервера Nginx, то проблем с установкой в Windows 10 не было.

Как установить и запустить сервер Nginx на Windows 10 6

Чтобы остановить Nginx, вы можете завершить его из окна Диспетчер задач.

Как установить и запустить сервер Nginx на Windows 10 7

Запуск Nginx на компьютере с ОС Windows

Для запуска Nginx, вы должны использовать Internet Information Services (IIS), который является веб-сервером Microsoft, обслуживающим запрошенные HTML страницы или файлы. Вы можете включить его в меню Turn Windows Features On or Off в Панели управления. Проверьте необходимые поля для Web Management Tools и IIS Management Console.

Как установить и запустить сервер Nginx на Windows 10 8

Для включения IIS на вашем компьютере потребуется некоторое время.

Как установить и запустить сервер Nginx на Windows 10 9

Менеджер IIS Manager можно открыть непосредственно из меню Пуск. Здесь вы сможете получить доступ к веб-сайту по умолчанию, который обычно расположен по адресу “inetpub wwwroot”. Он также известен как корень веб-приложения.

Полезно изменить физический путь этого корня в более подходящую папку. Я создал новую папку “Work” в C:\ и изменил физический путь на “C:\Work”.

Как установить и запустить сервер Nginx на Windows 10 10

После этого перейдите в папку Nginx, которую переименовали в файлах программы. Нажмите “Conf” и выберите “nginx.conf”. Этот файл можно редактировать с помощью текстового редактора Notepad++.

Как установить и запустить сервер Nginx на Windows 10 11

В Notepad++ измените корень на отредактированный физический путь, о котором мы говорили выше.

Как установить и запустить сервер Nginx на Windows 10 12

Вы можете отредактировать файл index.html в корневой папке на отдельной вкладке. Измените текст на то, что вы хотите, чтобы веб-сервер отображался на экране.

Как установить и запустить сервер Nginx на Windows 10 13

Теперь снова запустите программу Nginx.exe и введите “localhost” в окне браузера. Веб-сервер Nginx выделит сделанные вами изменения.

Как установить и запустить сервер Nginx на Windows 10 14

На сайте ресурсов Nginx представлен полный список веб-приложений, которые можно использовать для запуска на Windows PC.

Вывод

Nginx является одной из ведущих компаний по разработке веб-серверов, которая, как ожидается, затмит Apache в будущем. Кроме того, он быстрее, может справляться с большим количеством параллельных задач и надежен. Подводя итог, можно сказать, что если у вас есть простой сайт, который вы хотите подключить к Nginx, вы можете сделать это прямо сейчас без каких-либо проблем.


Спасибо, что читаете! На данный момент большинство моих заметок, статей и подборок выходит в telegram канале «Левашов». Обязательно подписывайтесь, чтобы не пропустить новости мира ИТ, полезные инструкции и нужные сервисы.


Респект за пост! Спасибо за работу!

Хотите больше постов в блоге? Подборок софта и сервисов, а также обзоры на гаджеты? Сейчас, чтобы писать регулярно и радовать вас большими обзорами, мне требуется помощь. Чтобы поддерживать сайт на регулярной основе, вы можете оформить подписку на российском сервисе Boosty. Или воспользоваться ЮMoney (бывшие Яндекс Деньги) для разовой поддержки:


Заранее спасибо! Все собранные средства будут пущены на развитие сайта. Поддержка проекта является подарком владельцу сайта.

Nginx is an open-source, high-performance HTTP server and reverse proxy server. It also functions as a mail proxy server and a generic TCP/UDP proxy server. Renowned for its stability, rich feature set, simple configuration, and low resource consumption, Nginx is often used as a web server or reverse proxy.

This article provides a comprehensive guide on how to install Nginx on a Windows-based operating system. It is worth noting that while Nginx does provide a Windows version, it is mostly recommended for development and testing purposes. For production environments, Linux distributions are typically preferred.

Prerequisites

Before you start with the installation process, make sure you have administrative rights on your Windows system, as they are required for software installation. Additionally, ensure your system meets the minimum hardware requirements for Nginx.

Step 1: Downloading Nginx

  1. Go to the Nginx download page.
  2. Under the “Mainline version”, click on the zip file link for the latest Windows version. The file will start downloading.Installing Nginx on Windows
    Downloading Nginx for Windows

Step 2: Extracting Nginx

  1. Once downloaded, locate the zip file, typically in your Downloads folder.
  2. Extract the zip file to your desired location. For this guide, we will use C:\nginx.Installing Nginx on Windows
    Extracted Nginx code in C:\nginx directory

Step 3: Running Nginx

  1. Open the Command Prompt with administrative privileges. You can do this by searching for ‘cmd’ in the Start menu, right-clicking on Command Prompt, and selecting “Run as administrator”.
  2. Navigate to the directory where you extracted Nginx. You can do this by typing cd C:\nginx and hitting Enter.
  3. Start Nginx by typing start nginx and hitting Enter.
    cd C:\nginx 
    start nginx.exe  
    

    How to Install Nginx on Windows

    Starting Nginx service on Windows
  4. Nginx should now be running on your Windows machine. You can check this by opening a web browser and navigating to http://localhost. If Nginx has started successfully, you will see a welcome page.How to Install Nginx on Windows
    Verify Nginx on Windows

Step 4: Managing Nginx

Here are some basic commands you can use to manage Nginx:

  • To stop Nginx, use the command `nginx -s stop`.
  • To quit Nginx gracefully, use `nginx -s quit`.
  • To reload the Nginx configuration file, use `nginx -s reload`.
  • To reopen the Nginx log files, use `nginx -s reopen`.

Remember to run these commands from the directory where Nginx is installed.

Step 5: Configuring Nginx

The primary configuration file for Nginx is nginx.conf, located in the conf subdirectory of the directory where Nginx was extracted. The configuration file is well-commented and provides a good starting point for configuring your server.

For Nginx to serve your website, you need to edit this file with your specific parameters. You may need to set up server blocks (similar to Apache’s virtual hosts) to specify the document root and other parameters for your website.

After making changes to the configuration file, remember to reload Nginx so that the changes take effect.

Conclusion

This guide provided a basic introduction to installing Nginx on a Windows system. While this should get you started, Nginx’s true power comes from its extensive configurability, allowing you to optimize it for your specific needs. Be sure to check out the official Nginx documentation for more detailed information on how to harness this power.

Nginx is a web server that is very popular with Linux and BSD systems. It can also be installed on Windows as long as you can live with performance limitations that have not been mitigated so far. You can still host a web server or a customer/employee portal from the comfort of your Windows laptop. To install and run Nginx successfully on Windows, follow the steps below.

Content

  • Installing Nginx in Windows
  • How to Start Nginx on Windows
  • 1. Using Nginx Application File
  • 2. Using PowerShell
  • 3. Using IIS Manager
  • How to Configure Nginx For Windows
  • Example Application of Nginx in Windows
  • Frequently Asked Questions

Tip: if all you need is a local web server to test your applications, here are the ways to set up a local web server in Windows.

Installing Nginx in Windows

To get started, we will need to install Nginx on your Windows laptop or PC. There are no conventional Nginx installers with this operating system. You will need to download one of its online versions and save it to a C: drive location of your PC.

  1. Select the version you want and download its zip file to your PC. Nginx recommends using the «mainline version» as it comes with the latest features. If you don’t need those features, the most recent stable version will work too.
Downloading the mainline version of Nginx from its official website.
  1. Once downloaded, extract the new folder by right-clicking on it. You may also use popular compression software such as 7-zip or WinRAR.
Right-click to extract all files for the downloaded Nginx installer software.
  1. Move the entire folder that came with the built-in download copy into the C: drive. In this example, we moved it to «Program Files» but it can be saved at any location on your PC including D drive.
Moving extracted Nginx folder to the Program Files.
  1. Select and double-click the «Nginx.exe» file. It has now been activated for further use. We will run Nginx from this location as a default web service program.
Double-click Nginx application inside the Program Files folder.
  1. If you have enabled Windows SmartScreen filter, it may prevent the Nginx installer from running. Click «More info» to bypass the limitation.
Click "More info" on the SmartScreen blocking Nginx application window.
  1. Click the «Run anyway» text to run the nginx.exe file.
SmartScreen blocks Nginx application which you can run anyway.
  1. You may further run into a Windows Defender firewall block screen while running the Nginx server, which has to be allowed by you. Once done, you can readily use Nginx on your Windows device.
Windows Defender firewall has blocked Nginx application. Click Allow access to run it.

Do you know: wondering what is the difference between Nginx and Apache? We have the answers here.

There are multiple ways to run Nginx on your Windows PC depending on your end use requirements. You can use these methods simultaneously. For example, you can launch the Nginx server using its application file or from PowerShell.

1. Using Nginx Application File

Nginx has a built-in application file that you can double-click as described in above section. You will need to bypass any restrictions due to SmartScreen or Windows Defender.

  1. Once done, go to your default browser and type localhost. Microsoft Edge is the browser used in the below example.
  2. If you see a screen saying the Nginx web server is successfully installed and working, it means there were no problems with your Nginx installation in Windows.
Edge browser in Windows showing Nginx default script after entering "localhost" on the address bar.
  1. To stop Nginx, you can end it from the Task Manager window. If you can’t terminate it directly from the Processes, right click to select «Go to details.»
Right click to select "Go to Details" for the Nginx process in Task Manager.
  1. Identify all instances of Nginx.exe and right click to end each task.
Right click to select "End task" tp terminate Nginx process inside Task Manager inside the Details window.
  1. Ignore any warning such as «do you want to end Nginx.exe.» Click «End process» to continue with the termination.
Click "End process" to terminate Nginx.exe from the Task Manager.
  1. When you type localhost, you will see a «can’t reach this page» screen on your browser web page.
Nginx localhost displaying "Can't reach this page" error on browser.

2. Using PowerShell

The best part of Nginx is that it can run as an automated script from PowerShell and also the Command Prompt. We will demonstrate that for PowerShell below.

  1. Launch PowerShell in Administrator mode.
Running PowerShell as administrator.
  1. Go back to the folder where you saved the Nginx application, and right-click to go to its Properties. Here you can copy the exact folder path. In this example, it is «C:\nginx-1.25.1\nginx-1.25.1»
Location path of Nginx application file in installed Nginx folder.
  1. Change the PowerShell directory to point to the above path.
cd Path of Nginx installer
Redirecting PowerShell to Nginx application folder path.
  1. To initiate the Nginx server, type the following command.
Start Nginx in PowerShell in Administrator mode.
  1. You can view Nginx.exe process instances in Task Manager nested under Windows PowerShell.
Nginx running as background processes in PowerShell window as seen in Task Manager.
  1. On Windows, Nginx can be run as a standard console app. For managing it, the following simple commands are frequently used:
nginx -s stop Rapid shutdown
nginx -s quit Graceful shutdown
nginx -s reload Changing configuration, starting new worker processes with a new configuration, graceful shutdown of old worker processes
nginx -s reopen Reopening log files
  1. If you encounter any error such as «the command nginx was not found, but does exist in the current location,» PowerShell will prompt you to use a different command. In the following example, we have replaced all instances of nginx with /.nginx, using them to reload and quit the program.
List of Nginx commands in PowerShell window.

3. Using IIS Manager

You can also use Internet Information Services (IIS) to run Nginx which is a Microsoft web server that serves requested HTML pages or files. In the past, it was compulsory but it’s no longer the case.

  1. You can enable it in «Turn Windows Features On or Off» in the Control Panel. Check the required fields for «Web Management Tools» and «IIS Management Console.»
Turn IIS Management Console On under the Internet Information Services.
  1. It will take a while for IIS to be enabled on your computer as the changes are applied.
Applying changes to turn on Windows features in the window.
  1. You will see a success status that «Windows completed the requested changes.»
Windows completed the requested changes to turn on the required features with IIS Console.
  1. You can open IIS Manager directly from the Start menu. Always open it in Administrator mode.
Open IIS Manager app from Start menu in Administrator mode.
  1. Here, you will be able to access the default website, which is usually located at «inetpub wwwroot.» This is also known as the web application root. You can look for it in File Explorer through a simple search.
  2. When you double-click on the «default web site» option in IIS Manager, it should lead to this new folder. Alternatively, you can right-click the menu and select «Explore» for the same result.
Root folder of PC as identified using IIS Manager.
  1. Once your IIS Console is enabled, you can view its webpage by typing localhost on your default browser.
Local Host in Nginx pointing to IIS website.

How to Configure Nginx For Windows

To run Nginx in Windows, all desired changes are affected from various strings modified in the «index.html» and «nginx.conf» files in the installation folder. These strings are usually edited using the Notepad text editor, but you can use any other editor such as Atom, Notepad++ or Visual Studio Code. In this case, we will edit the configuration file using Notepad++.

  1. Go to the folder where you saved your Nginx application. Click the «html» subfolder.
HTML subfolder in Nginx folder.
  1. Right click to select «Edit with Notepad++» for the index.html file.
Right click to edit Index HTML file in Nginx folder using Notepad++.
  1. You can edit the index.html file in the root folder in a new or separate tab. Change the text to what you want the web server to display on the screen.
  2. Don’t forget to click the «Save» button on top once you’re done.
  3. Exit the Nginx.exe program using «End Task» as shown in above section and restart it.
Editing HTML file of Nginx with text changes and saving the file.
  1. Type localhost in a browser window. The Nginx web server will highlight the edits you made.
Edited text viewed as localhost on the default browser.
  1. After this, click «Conf» and right click to select «nginx.conf» followed by «Edit with Notepad++.»
Right click to edit Nginx conf file with Notepad++.
  1. Find the location of the root and change it from the default html to any other physical path.
Changing Conf File Root path using Notepad++.

To know more about Nginx commands, including the documentation, visit this link.

Example Application of Nginx in Windows

Nginx supports multiple applications in Windows, such as web server, load balancer, reverse proxy, or even host your own Youtube site. The Nginx resources site has a full list of web server applications which you can use to run various applications on Windows PC.

For example, you can use Nginx in Windows to link to a webpage such as a customer login page. Once you make the configuration changes in the «nginx.conf» file, your end users will be able to access the login page on their end.

  1. Go back to the «nginx.conf» file shared in the previous section. Instead of «somename,» you need a domain name for the server to access.
Adding a domain name in Conf file of Nginx.
  1. Go to «location» and modify the text using an «api,» followed by a proxy server added with an «http» ping. This should point to any login page you want this page to direct to. Here we have a «proxy_pass» field which has a «127.0.0.1′ URL local to your Windows machine.
  2. Save the file and run the «Nginx.exe» program in Admin mode.
Replace Proxy path with a login page in Nginx Conf file.
  1. As shown here, 127.0.0.1 is what Nginx.exe points to, and this is the path you can modify in above Conf file to point to an external customer portal or web server.

127.0.0.1 page visible in browser with Nginx.

Frequently Asked Questions

How to solve Nginx’s «The system cannot find the path specified» error in Windows?

Sometimes while running Nginx in Windows Command Prompt/PowerShell, you may run into a «System cannot find the path specificed» error. To avoid it, go to the folder where you saved the Nginx.exe application, and right click on it to view its properties, which will give the exact path it is located. There could be a few other reasons behind this, and we have a detailed guide to fix the issue.

What are the disadvantages of Nginx in Windows?

Even though it supports Windows, Nginx is not the best choice for the operating system. Its biggest disadvantage is that it’s incapable of multitasking. For instance, you can execute only one process at a time. If you are running a web server, your Windows machine will be occupied with that one task. This poses challenges in scalability, and one Windows device isn’t sufficient to work with Nginx.

How popular is Nginx?

Nginx is one of the leading web server companies today. Also, it is faster, can handle more concurrent issues and is reliable. To summarize, if you have a simple website you want to connect to Nginx, you can do it right now without any problems. Read on to check out the comparison of Nginx to OpenLiteSpeed.

All images and screenshots by Sayak Boral.

Sayak Boral

Sayak Boral is a technology writer with over eleven years of experience working in different industries including semiconductors, IoT, enterprise IT, telecommunications OSS/BSS, and network security. He has been writing for MakeTechEasier on a wide range of technical topics including Windows, Android, Internet, Hardware Guides, Browsers, Software Tools, and Product Reviews.

Subscribe to our newsletter!

Our latest tutorials delivered straight to your inbox

Из данного HOWTO Вы узнаете как установить и настроить связку nginx + php (в режиме FastCGI) + СУБД MySQL для работы под операционной Microsoft Windows.

Мы подробно рассмотрим вопросы установки, базовой и расширенной настройки, а также безопасности.

В статье приводятся примеры скриптов запуска и остановки, а также примеры файлов конфигурации nginx и php.

Подробности смотрите под катом.

Шаг 1. Подготовка к установке

Для начала рекомендуем в корне системного диска создать каталог nginx (например, c:\nginx\), а в нём подкаталоги public_html, php и mysql. Лучше всего связка работает, когда все основные компоненты находятся в одном каталоге. В каталог php мы будем устанавливать интерпретатор PHP5, в mysql соответственно данную СУБД, а в public_html — файлы главного сайта.

Разместив все компоненты таким образом, Вы сделаете пакет перемещаемым (Portable) и готовым к работе с любого компьютера.

Шаг 2. Загрузка необходимых компонентов

Нам потребуются следующие компоненты:

  1. PHP — http://windows.php.net/download/. Вам необходимо скачать версию с инсталлятором (*.msi) в варианте Thread Safe;
  2. MySQL — http://dev.mysql.com/downloads/mysql/. Также скачайте версию с msi-инсталлятором;
  3. nginx — http://nginx.org/ru/download.html. Скачайте последнюю версию;
  4. RunHiddenConsole — http://redmine.lighttpd.net/attachments/660/RunHiddenConsole.zip.

Шаг 3. Установка компонентов

По окончании скачивания приступайте к установке компонентов согласно данному алгоритму:

  1. распакуйте архив с nginx в созданный на шаге 1 каталог в корне (например, c:\nginx\). Далее в данном HOWTO будет использоваться именно этот каталог, поэтому если Вы изменили путь, сделайте соответствующие правки;
  2. установите PHP в каталог c:\nginx\php\:
    1. на этапе выбора типа установки (Web Server Setup) обязательно выберите вариант «Other CGI«, иначе модули, необходимые для работы PHP в режиме FastCGI не будут установлены;
      PHP - Web Server Setup
      PHP — Web Server Setup
    2. на этапе выбора необходимых модулей (Choose Items to Install) обязательно выберите MySQL, MySQLi и OpenSSL (если хотите далее настроить SSL). Также рекомендуется выбрать модули, необходимые для большинства CMS: bzip2, Curl, Exif, GD2, Gettext, XML. Если Вы забыли что-то нужное и оно Вам потребуется, Вы всегда сможете доустановить/удалить эти компоненты, снова запустив программу установки PHP и выбрав пункт Change.
      PHP - выбор компонентов
      PHP — выбор компонентов
  3. установите СУБД MySQL в каталог c:\nginx\mysql\. Здесь нет ничего сложного. В мастере конфигурации выберите стандартную конфигурацию и обязательно задайте пароль администратора (пароль встроенной учётной записи суперпользователя root);
  4. распакуйте архив RunHiddenConsole.zip в каталог c:\nginx\.

Шаг 4. Создание скриптов запуска и остановки

Для быстрого запуска набора Вам потребуется создать в каталоге c:\nginx\ 3 файла: start.cmd, shutdown.cmd и restart.cmd, предназначенные соответственно для запуска, остановки и перезапуска серверов.

Листинг файла start.cmd (запуск сервера):

@echo off
echo Starting servers...
set PHP_FCGI_MAX_REQUESTS=0
set SRVPATH=C:\nginx
net start MySQL
start /D%SRVPATH% nginx.exe
%SRVPATH%\RunHiddenConsole.exe %SRVPATH%\php\php-cgi.exe -b 127.0.0.1:9000 -c %SRVPATH%/php/php.ini

Листинг файла shutdown.cmd (остановка сервера):

@echo off
echo Shutting down servers...
taskkill /IM nginx.exe /F
taskkill /IM php-cgi.exe /F
net stop MySQL

Листинг файла restart.cmd (перезапуск сервера):

@echo off
echo Shutting down servers...
taskkill /IM nginx.exe /F
taskkill /IM php-cgi.exe /F
net stop MySQL
echo Starting servers...
set PHP_FCGI_MAX_REQUESTS=0
set SRVPATH=C:\nginx
net start MySQL
start /D%SRVPATH% nginx.exe
%SRVPATH%\RunHiddenConsole.exe %SRVPATH%\php\php-cgi.exe -b 127.0.0.1:9000 -c %SRVPATH%/php/php.ini

Если Вы изменили путь со стандартного C:\nginx\, на что-то другое, внесите соответствующие правки в скрипты.

Если требуется запускать сервер nginx+php+mysql при загрузке системы, то добавьте задание на автозапуск скрипта start.cmd с помощью оснастки Назначенные задания Windows.

Откройте файл c:\nginx\conf\nginx.conf в любом текстовом редакторе (я рекомендую Notepad++).

1. Измените строку:

worker_processes  1;

Здесь вместо 1 укажите количество рабочих процессов nginx. Рекомендуется указывать число, равное количеству ядер процессора.

2. Уберите символ комментария (решётку) у строки:

error_log  logs/error.log;

Это позволит включить запись логов ошибок в файл error.log, который Вы всегда найдёте в каталоге c:\nginx\logs\.

3. Измените значение директивы server{} для nginx без использования SSL:

server {
 listen 80 default;
 server_name localhost;

 server_tokens off;

 #charset koi8-r;

 #access_log logs/access.log  main;

 location / {
 root c:/nginx/public_html;
 index index.html index.htm index.php;
 }

 location ~ \.php$ {
 fastcgi_pass 127.0.0.1:9000;
 fastcgi_index index.php;
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 include fastcgi_params;
 }

 location ~ /\.ht {
 deny all;
 }

 #error_page 404 /404.html;

 error_page 500 502 503 504 /50x.html;
 location = /50x.html {
 root html;
 }
}

Если Вы хотите использовать SSL, Вам потребуется совсем иной конфиг:

server {
 listen 443 default;
 server_name localhost;

 server_tokens off;

 ssl on;
 ssl_certificate C:/nginx/private/ssl_cert_domain.pem;
 ssl_certificate_key C:/nginx/private/ssl_cert_domain.key;

 ssl_session_timeout 5m;

 ssl_protocols SSLv2 SSLv3 TLSv1;
 ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
 ssl_prefer_server_ciphers on;

 #charset koi8-r;

 #access_log logs/access.log  main;

 location / {
 root c:/nginx/public_html;
 index index.html index.htm index.php;
 }

 location ~ \.php$ {
 fastcgi_pass 127.0.0.1:9000;
 fastcgi_index index.php;
 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
 include fastcgi_params;
 fastcgi_param HTTPS on;
 }

 #error_page 404 /404.html;

 error_page 500 502 503 504 /50x.html;
 location = /50x.html {
 root html;
 }

 location ~ /\.ht {
 deny all;
 }
}

Здесь C:/nginx/private/ssl_cert_domain.pem — файл сертификата SSL, а C:/nginx/private/ssl_cert_domain.key — закрытый ключ для него. Внимание! При старте сервера у Вас запросят пароль для расшифровки закрытого ключа, поэтому чтобы не вводить его постоянно, во время создания (получения) сертификата оставьте поле ввода пароля пустым (это конечно небезопасно, но экономит время во время запуска сервера). В новых версиях возможно появится функция указания пароля в конфиге (как у Apache).

Вы можете включить ведение логов доступа (access.log), убрав символ комментария у строки #access_log  logs/access.log  main;.

Вы также можете переопределить страницы ошибок 404, 500, 502, 503, 504 и 403 путём указания в директиве error_page кода ошибки и имени файла, который будет отображаться при её возникновении.

Шаг 6. Настройка php и безопасность

Откройте текстовый файл C:\nginx\php\php.ini в любом текстовом редакторе. Из соображений безопасности рекомендуем изменить строку

safe_mode = Off

на

safe_mode = On

Также найдите в файле строку

disable_functions =

и замените её на следующую:

disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source

Эти действия включат безопасный режим для PHP (Safe Mode), при котором запрещены большинство небезопасных функций и исполнение файлов, а также отключит ряд потенциально уязвимых функций. Внимание! Если Ваша CMS не работает при включённом режиме PHP Safe Mode, отключите его, либо поставьте правильную CMS ;-).

Если Вы являетесь разработчиком и хотите видеть ошибки и сообщения PHP, то найдите строку

display_errors = Off

и замените её на

display_errors = On

Для исправления опасной уязвимости в PHP, позволяющей выполнять PHP-код из загружаемых файлов, найдите в php.ini строку

;cgi.fix_pathinfo=1

уберите символ комментария (;) около неё и замените на следующую:

cgi.fix_pathinfo = 0

Дальнейшие настройки файла изменять не требуется — всё уже настроено оптимально для большинства применений программой установки PHP.

Шаг 7. Обработка нескольких PHP-файлов одновременно

К сожалению, PHP в Windows не умеет создавать копии своих экземпляров, поэтому придётся заранее запускать несколько копий и описать их использование в конфиге nginx.

В файле start.cmd пропишите запуск php-cgi.exe на разные номера портов:

%SRVPATH%\RunHiddenConsole.exe %SRVPATH%\php\php-cgi.exe -b 127.0.0.1:9000 -c %SRVPATH%/php/php.ini
%SRVPATH%\RunHiddenConsole.exe %SRVPATH%\php\php-cgi.exe -b 127.0.0.1:9001 -c %SRVPATH%/php/php.ini
%SRVPATH%\RunHiddenConsole.exe %SRVPATH%\php\php-cgi.exe -b 127.0.0.1:9002 -c %SRVPATH%/php/php.ini
%SRVPATH%\RunHiddenConsole.exe %SRVPATH%\php\php-cgi.exe -b 127.0.0.1:9003 -c %SRVPATH%/php/php.ini
%SRVPATH%\RunHiddenConsole.exe %SRVPATH%\php\php-cgi.exe -b 127.0.0.1:9004 -c %SRVPATH%/php/php.ini

Запустите столько процессов, сколько вам потребуется (обычно достаточно 5-20). В нашем примере используется 5 экземпляров с номерами портов 9000 — 9004.

Откройте файл nginx.conf в текстовом редакторе и перед директивой server {} пропишите следующие строки:

upstream backend {
server 127.0.0.1:9000;
server 127.0.0.1:9001;
server 127.0.0.1:9002;
server 127.0.0.1:9003;
server 127.0.0.1:9004;
}

Теперь откройте файл fastcgi_params и в самом начале пропишите следующее:

fastcgi_connect_timeout 1;
fastcgi_next_upstream timeout;
fastcgi_pass backend;

Обязательно уберите fastcgi_pass 127.0.0.1:9000; во всех директивах location.

Пример готового конфига nginx.conf:

worker_processes 4;

error_log logs/error.log;

events {
worker_connections 1024;
}

http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
upstream backend {
server 127.0.0.1:9000;
server 127.0.0.1:9001;
server 127.0.0.1:9002;
server 127.0.0.1:9003;
server 127.0.0.1:9004;
}
server {
listen 80 default;
server_name localhost;
server_tokens off;
location / {
root C:/nginx/public_html;
index index.html index.htm index.php;
location ~ \.php$ {
include fastcgi_params;
}
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location ~ /\.ht {
deny all;
}
}
}

Пример конфига, использующего SSL:

worker_processes 4;

error_log logs/error.log;

events {
worker_connections 1024;
}

http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
upstream backend {
server 127.0.0.1:9000;
server 127.0.0.1:9001;
server 127.0.0.1:9002;
server 127.0.0.1:9003;
server 127.0.0.1:9004;
}
server {
listen 443 default;
server_name localhost;
server_tokens off;
ssl on;
ssl_certificate C:/nginx/private/ssl_cert_domain.pem;
ssl_certificate_key C:/nginx/private/ssl_cert_domain.key;
ssl_session_timeout 5m;
ssl_protocols SSLv2 SSLv3 TLSv1;
ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
ssl_prefer_server_ciphers on;
location / {
root C:/nginx/public_html;
index index.html index.htm index.php;
location ~ \.php$ {
include fastcgi_params;
fastcgi_param HTTPS on;
}
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location ~ /\.ht {
deny all;
}
}
}

Пример файла fastcgi_params:

fastcgi_connect_timeout 1;
fastcgi_next_upstream timeout;
fastcgi_pass backend;

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;
fastcgi_index  index.php;

Шаг 8. Тестирование и заключение

Запустите серверы и создайте в каталоге C:\nginx\public_html\ файл test.php со следующим содержанием:

<?php
phpinfo();
?>

Откройте этот файл в браузере по адресу http://localhost/test.php и если Вы увидели информацию об установленном сервере, значит всё работает корректно и Вы можете приступать к использованию сервера.

Шаг 9. Готовые примеры файлов конфигурации

По многочисленным просьбам мы решили выложить примеры всех файлов конфигурации nginx в Git-репозитории. В данный момент доступно три разных готовых конфига:

  • nginx_simple.conf — простейший конфиг для запуска одного сайта без поддержки SSL;
  • nginx_ssl.conf — конфиг для запуска одного сайта с поддержкой SSL;
  • nginx_vhosts.conf — специально настроенный конфиг с относительными путями, поддержкой SSL, виртуальных хостов (позволяет держать несколько сайтов на одном сервере) и отдельных логов.

Там же вы найдете готовые скрипты запуска и остановки сервера, а также файл конфигурации PHP.

  • Как настроить iptv на windows
  • Как настроить nvidia для игр на windows 10 ноутбуке видеокарту
  • Как настроить ntp сервер windows server 2019
  • Как настроить ip адрес на компьютере windows 10 проводной интернет
  • Как настроить msconfig на windows 10