Nginx and PHP Setup on Windows
For local development you could also use Nginx with PHP as an replacement for XAMPP.
Install Nginx
- Download Nginx for Windows: http://nginx.org/en/download.html | Direct: nginx-1.19.7.zip
- Extract the ZIP file to
c:\nginx - Open the file
c:/nginx/config/nginx.confand replace theserver { ... }section with this configuration:
server {
listen 80;
server_name localhost;
index index.php;
error_log c:/nginx/logs/localhost.error.log;
access_log c:/nginx/logs/localhost.access.log;
root c:/nginx/html;
location / {
try_files $uri /index.php$is_args$args;
}
location ~ \.php {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:9123;
}
}
- Create a file
c:/nginx/html/index.phpand copy/paste this content:
- To start the webserver run:
cd c:\nginxstart nginx
- Allow the windows firewall access
- Run the tasklist command-line utility to see nginx processes:
tasklist /fi "imagename eq nginx.exe"
nginx runs as a standard console application (not a service), and it can be managed using the following commands:
nginx -s stopfast shutdownnginx -s quitgraceful shutdownnginx -s reloadchanging configuration, starting new worker processes with a new configuration, graceful shutdown of old worker processesnginx -s reopenre-opening log filestaskkill /IM nginx.exe /FClose all nginx processes
Install PHP
- Download PHP for Windows Thread Safe x64: php-8.3.12-Win32-vs16-x64.zip
- Extract the ZIP file to:
c:\nginx\php - Make sure that the file
C:\nginx\php\php-cgi.exeexists. - Create a new file:
c:\nginx\php\php.iniand copy/paste this content:
[PHP] engine = On short_open_tag = Off implicit_flush = Off zend.enable_gc = On expose_php = Off max_execution_time = 30 max_input_time = 60 memory_limit = 512M error_reporting = E_ALL display_errors = On display_startup_errors = On log_errors = On variables_order = "GPCS" request_order = "GP" register_argc_argv = Off auto_globals_jit = On post_max_size = 8M default_mimetype = "text/html" default_charset = "UTF-8" include_path = "." extension_dir = "c:\nginx\php\ext" enable_dl = Off file_uploads = On upload_max_filesize = 2M max_file_uploads = 20 allow_url_fopen = On allow_url_include = Off default_socket_timeout = 60 extension=curl extension=fileinfo extension=gd extension=gettext extension=intl extension=mbstring extension=mysqli extension=openssl extension=pdo extension=pdo_mysql extension=sqlite3 [Session] session.save_handler = files session.save_path = "c:\nginx\temp" session.use_strict_mode = 0 session.use_cookies = 1 session.use_only_cookies = 1 session.name = PHPSESSID session.auto_start = 0 session.cookie_lifetime = 0 session.cookie_path = / session.cookie_domain = session.cookie_httponly = session.cookie_samesite = session.serialize_handler = php session.gc_probability = 1 session.gc_divisor = 1000 session.gc_maxlifetime = 1440 session.cache_limiter = nocache session.cache_expire = 180 session.use_trans_sid = 0 session.sid_bits_per_character = 5
To start PHP with FastCGI run:
cd c:\nginx\phpphp-cgi.exe -b 127.0.0.1:9123- Open
http://localhost - You should see the phpinfo page.
XDebug Setup
- Follow these installation instructions: https://odan.github.io/2020/12/03/xampp-xdebug-setup-php8.html
Есть нужен веб-сервер для Windows, идеально подойдет веб-сервер Nginx с подключенным PHP через FastCGI. В статье будет показана настройка и связка Nginx с PHP на примере Windows 11. Аналогично происходит настройка в Windows 7/8/10.
1. Структура каталогов под сервера
Удобно когда все сервера и сервисы установлены в отдельной папке. Я рекомендую сделать структуру аналогично моей.
Создаем на диске D:\ папку server (если диск один, то создаем на C). В папке server будет находится все что относится в веб-серверу, базы данных, файлы сайта.
Структура будет выглядеть так:
# Папка для серверов
D:\server\
# Папка для nginx
D:\server\nginx\
# Папка для PHP
D:\server\php\
# Папка для веб-сайтов
D:\server\www\
Создаем необходимые папки.
Подобная архитектура удобна тем, что все сервера находятся на отдельном диске в отдельной папке. Можно без проблем сделать резервное копирование, обновление серверов и так далее.
2. Установка и настройка nginx
2.1. Установка nginx
Заходим на официальный сайт Nginx https://nginx.org/ru/download.html и скачиваем последнею версию
Стабильная версия больше подойдет если nginx используется для рабочих веб-сайтов, а не используется для разработки, тестирования новых возможностей nginx.
Извлекаем скаченный архив в папку D:\server\nginx\
2.2. Конфигурация nginx (nginx.conf)
Теперь необходимо настроить сам nginx и его работу в связке с PHP.
Открываем файл конфигурации nginx.conf (в моем случае D:\server\nginx\conf\nginx.conf) и настраиваем веб-сервер nginx
# Базовый файл конфигурации nginx + PHP FastCGI
#user nobody;
worker_processes 1; # Количество запущенных процессов
#Лог ошибок
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024; # Количество подключений к одному процессу
}
http {
include mime.types;
default_type application/octet-stream;
# Лог доступа
access_log off;
#access_log logs/access.log main;
gzip on; # Использовать сжатие
# Разделов server может быть неограниченное количество
#
# Раздел server для домена сайта localhost по 80 порту
server {
listen 80; # Порт
server_name localhost; # Домен сайта
charset utf-8; # Кодировка сайта
error_log logs/localhost.error.log; # Лог ошибок сайта
access_log logs/localhost.access.log; # Лог доступа сайта
# Путь до папки сайта
root D:/server/www;
# Обработка всех URI запросов начинающихся с /
location / {
#root D:/server/www; # root определена в разделе server
index index.html index.php; # файлы в качестве индекса
}
# Настройка обработки php скриптов через PHP-FastCGI
#
# Обработка всех URI запросов оканчивающихся на .php
location ~ \.php$ {
# IP и порт PHP-FastCGI. С такими же параметрами нужно будет запускать php-cgi.exe
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
# Путь до php скриптов, $document_root - путь из параметра root (папка сайта)
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
}
Сохраняем и закрываем файл.
3. Установка и настройка PHP
3.1. Установка PHP
Заходим на сайт PHP https://windows.php.net/download и скачиваем последнею Non Thread Safe версию
Если в Windows не установлены Visual C++ Redistributable для Visual Studio 2015-2019, их необходимо скачать (vc_redist.x64.exe и vc_redist.x86.exe) и установить.
Извлекаем скаченный архив в папку D:\server\php\
3.2. Конфигурация PHP (php.ini)
По умолчанию в PHP содержатся два примера конфигурации php.ini-production и php.ini-development. Версия production используется для рабочих сайтов, в ней ошибки только записываются в лог файлы веб-сервера. Версия development используется при разработке, в ней ошибки выводятся на веб-страницу и записываются в лог файлы.
Копируем и переименовываем файл php.ini-production или php.ini-development в php.ini (это основной файл конфигурации PHP).
Открываем в тестовом редакторе файл php.ini (в моем случае D:\server\php\php.ini), находим параметр extension_dir и указываем папку с расширениями PHP
; Раскомментируем параметр для Windows (относительный путь)
extension_dir = "ext"
; Или можно указать полный путь до папки с расширениями
;extension_dir = "D:\server\php\ext"
Далее находим раздел Dynamic Extensions и включаем необходимые расширения
Сохраняем и закрываем файл.
4. Скрипты запуска и остановки веб-сервера
В папке D:\server\ будут находится скрипты для управления веб-сервером.
После запуска php-cgi.exe (PHP FastCGI), он будет работать в открытом окне консоли. Если это не желательно, скачиваем утилиту RunHiddenConsole.exe в папку D:\server\ и тогда дальнейший запуск php-cgi.exe будет происходить через данную утилиту.
Создаем скрипт запуску веб-сервера web-start.bat
:: Запуск PHP FastCGI
:: Если файл RunHiddenConsole.exe существует, то запускаем PHP через утилиту
if exist "RunHiddenConsole.exe" (
:: PHP будет запущен в скрытом режиме
RunHiddenConsole.exe "php\php-cgi.exe" -b 127.0.0.1:9000 -c "php\php.ini"
) else (
start php\php-cgi.exe -b 127.0.0.1:9000 -c "php\php.ini"
)
:: Запуск nginx
cd nginx
start nginx.exe
Создаем скрипт остановки веб-сервера web-stop.bat
taskkill /f /IM nginx.exe
taskkill /f /IM php-cgi.exe
Для удобства создаем скрипт перезапуска веб-сервера web-restart.bat
call web-stop.bat
call web-start.bat
В результате папка server выглядит следующим образом
5. Проверка веб-сервера nginx + PHP
Создаем в папке D:\server\www\ файл index.php следующего содержимого
<?php
phpinfo();
?>
Запускаем веб-сервер скриптом web-start.bat
Открываем в браузере http://localhost/ и если все нормально, будет выведена информация о PHP.
nginx в связке с PHP успешно установлены, настроены и работают.
Если что-то не работает, смотрим лог файлы nginx (D:\server\nginx\logs\) или запускаем PHP без скрытия консоли, чтобы увидеть ошибки в ней.
Из данного HOWTO Вы узнаете как установить и настроить связку nginx + php (в режиме FastCGI) + СУБД MySQL для работы под операционной Microsoft Windows.
Мы подробно рассмотрим вопросы установки, базовой и расширенной настройки, а также безопасности.
В статье приводятся примеры скриптов запуска и остановки, а также примеры файлов конфигурации nginx и php.
Подробности смотрите под катом.
Шаг 1. Подготовка к установке
Для начала рекомендуем в корне системного диска создать каталог nginx (например, c:\nginx\), а в нём подкаталоги public_html, php и mysql. Лучше всего связка работает, когда все основные компоненты находятся в одном каталоге. В каталог php мы будем устанавливать интерпретатор PHP5, в mysql соответственно данную СУБД, а в public_html — файлы главного сайта.
Разместив все компоненты таким образом, Вы сделаете пакет перемещаемым (Portable) и готовым к работе с любого компьютера.
Шаг 2. Загрузка необходимых компонентов
Нам потребуются следующие компоненты:
- PHP — http://windows.php.net/download/. Вам необходимо скачать версию с инсталлятором (*.msi) в варианте Thread Safe;
- MySQL — http://dev.mysql.com/downloads/mysql/. Также скачайте версию с msi-инсталлятором;
- nginx — http://nginx.org/ru/download.html. Скачайте последнюю версию;
- RunHiddenConsole — http://redmine.lighttpd.net/attachments/660/RunHiddenConsole.zip.
Шаг 3. Установка компонентов
По окончании скачивания приступайте к установке компонентов согласно данному алгоритму:
- распакуйте архив с nginx в созданный на шаге 1 каталог в корне (например, c:\nginx\). Далее в данном HOWTO будет использоваться именно этот каталог, поэтому если Вы изменили путь, сделайте соответствующие правки;
- установите PHP в каталог c:\nginx\php\:
- на этапе выбора типа установки (Web Server Setup) обязательно выберите вариант «Other CGI«, иначе модули, необходимые для работы PHP в режиме FastCGI не будут установлены;
PHP — Web Server Setup - на этапе выбора необходимых модулей (Choose Items to Install) обязательно выберите MySQL, MySQLi и OpenSSL (если хотите далее настроить SSL). Также рекомендуется выбрать модули, необходимые для большинства CMS: bzip2, Curl, Exif, GD2, Gettext, XML. Если Вы забыли что-то нужное и оно Вам потребуется, Вы всегда сможете доустановить/удалить эти компоненты, снова запустив программу установки PHP и выбрав пункт Change.
PHP — выбор компонентов
- на этапе выбора типа установки (Web Server Setup) обязательно выберите вариант «Other CGI«, иначе модули, необходимые для работы PHP в режиме FastCGI не будут установлены;
- установите СУБД MySQL в каталог c:\nginx\mysql\. Здесь нет ничего сложного. В мастере конфигурации выберите стандартную конфигурацию и обязательно задайте пароль администратора (пароль встроенной учётной записи суперпользователя root);
- распакуйте архив 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.
Introduction
In this post, I will go over details of how to install Nginx webserver and PHP on Windows 10, 11 or Windows Server. I will show where to download and how to do the configuration of Apache and integration with PHP.
I will also discuss some advanced configuration options for the setup as well.
Installing Nginx Webserver
Apache webserver files and all related information is located on the Nginx Opensource Project website.
Download Apache Webserver
You can access the Nginx source code repository if you are planning to build it from scratch. In our case, I will download a prebuilt version of the software from here.
Note that there are two versions of the server available to download.
- Mainline: This is the latest with the newest features. It should be used for testing the latest features. I find it very usable to development purposes as well.
- Stable: Lastest stable version to be used in production.
Either one of these will work for this guide. I will download the stable version to match what I have in production on my servers.
Go ahead and download the zip file from the Nginx website.
Installing Nginx Webserver
Once your download is complete, you can unzip the files in any location on your computer. I am going to install all the files in the C:\apps\nginx\ folder.
The structure of the folder will be:
C:\apps\nginx>dir
Volume in drive C has no label.
Volume Serial Number is 6615-FCF1
Directory of C:\apps\nginx
04/09/2022 01:14 PM <DIR> .
04/09/2022 01:14 PM <DIR> ..
04/09/2022 01:10 PM <DIR> conf
04/09/2022 01:10 PM <DIR> contrib
04/09/2022 01:10 PM <DIR> docs
04/09/2022 01:10 PM <DIR> html
12/29/2022 01:47 PM <DIR> logs
04/09/2022 01:10 PM 3,751,936 nginx.exe
04/09/2022 01:14 PM <DIR> ssl-certs
04/09/2022 01:15 PM <DIR> temp
Copying the contents of the Nginx zip file is all that is required for a valid install of Nginx webserver on Windows.
In the next section I will go over details of running Nginx and serving file. But before we get to that let’s go over details of some important folders.
CONF Folder
Conf folder contains all configuration files, including the main nginx.conf file.
HTML Folder
html folder contains the default index.html file that comes with the webserver. html folder also has a 50x.html file that Nginx uses to show errors.
The default configuration will serve all files from this folder. You can override this behavior by using Virtual Host configurations. A setup I will review towards the end of this post.
LOGS folder
logs folder maintains logs, both access and error, for configured websites being served by Nginx.
Now that I have the default install complete, let’s go over details of running the webserver.
Running Nginx From Command Line
There are two ways to run Apache from the command line.
# First
C:\apps\nginx>nginx.exe
# Second
C:\apps\nginx>start nginx.exe
The first method will run the executable as a child process of the existing shell and will block until you exit the process by either killing the Nginx process through the Task Manager or by using another command prompt window and sending a stop or shutdown signal using the -s option to the nginx.exe executable.
C:\apps\nginx>nginx.exe -s stop (or use shutdown instead of stop)
This will usually shutdown Nginx but I have found that the signal does not work consistently on Windows and therefore I use the Task Manager to kill the process.
Note: Pressing CTRL+C does not stop the Nginx webserver. Even closing the command prompt will not kill the Nginx process.
The second method uses the start command and will create a new command window that will execute the nginx.exe process and will exit. Even though the command prompt will exit the Nginx webserver will continue running.
You can view the running process in Task Manager as well.
Validating Nginx Webserver Install
After Installing Nginx and running it from the command prompt you can go to the browser and open the URL http://localhost. The default index.html file will be viewable if all installation steps were correctly executed.
Installing Nginx as a Windows Service
Unlike Apache webserver on Windows, Nginx does not come with built-in commands to install it as a Windows service. You will have to download additional utilities to set it up as a service. Microsoft has a good article on how to create a user-defined service using Windows resource kit.
Another way to have Nginx start up when you login to Windows is by creating a link to nginx.exe from the Startup programs folder. Listed below are details on how to do this.
First press Windows+R key. This will pop open the run dialog. Enter shell:startup command.
This will open the startup folder showing list of programs Windows will start upon user login.
Create a new shortcut and browse to the Nginx folder and select nginx.exe.
Once this is complete you will have Nginx startup after logging in to Windows.
Installing PHP on Windows
To install PHP go to the website and download the latest version of PHP.
On the download page, you will find two different types of PHP downloads.
- NTS or Not thread-safe
- Thread-safe
I will be doing an install of PHP in FastCGI mode and therefore will be downloading the thread-safe version. Do note that NTS version has better performance.
Install PHP Locally
After downloading PHP zip file, unzip and copy the contents to a folder. I will install it at location C:\apps\lang\php. The folder contents will be:
C:\apps\lang\php>dir
Directory of C:\apps\lang\php
01/15/2023 11:58 AM <DIR> .
01/15/2023 11:58 AM <DIR> ..
01/15/2023 11:51 AM 137,728 deplister.exe
01/15/2023 11:51 AM <DIR> dev
01/15/2023 11:51 AM <DIR> ext
01/15/2023 11:51 AM <DIR> extras
01/15/2023 11:51 AM 1,609,728 glib-2.dll
01/15/2023 11:51 AM 18,944 gmodule-2.dll
01/15/2023 11:51 AM 30,422,016 icudt71.dll
01/15/2023 11:51 AM 3,031,552 icuin71.dll
01/15/2023 11:51 AM 60,928 icuio71.dll
01/15/2023 11:51 AM 2,253,312 icuuc71.dll
01/15/2023 11:51 AM <DIR> lib
01/15/2023 11:51 AM 5,192,704 libcrypto-3-x64.dll
01/15/2023 11:51 AM 42,496 libenchant2.dll
01/15/2023 11:51 AM 289,792 libpq.dll
01/15/2023 11:51 AM 209,920 libsasl.dll
01/15/2023 11:51 AM 303,616 libsodium.dll
01/15/2023 11:51 AM 1,646,080 libsqlite3.dll
01/15/2023 11:51 AM 380,928 libssh2.dll
01/15/2023 11:51 AM 776,192 libssl-3-x64.dll
01/15/2023 11:51 AM 3,272 license.txt
01/15/2023 11:51 AM 20,972 news.txt
01/15/2023 11:51 AM 228,352 nghttp2.dll
01/15/2023 11:51 AM 43 phar.phar.bat
01/15/2023 11:51 AM 65,969 pharcommand.phar
01/15/2023 11:51 AM 69,120 php-cgi.exe
01/15/2023 11:51 AM 38,400 php-win.exe
01/15/2023 11:51 AM 142,336 php.exe
01/15/2023 11:51 AM 75,124 php.ini-development
01/15/2023 11:51 AM 75,272 php.ini-production
01/15/2023 11:51 AM 35,840 php8apache2_4.dll
01/15/2023 11:51 AM 932,824 php8embed.lib
01/15/2023 11:51 AM 278,016 php8phpdbg.dll
01/15/2023 11:51 AM 9,049,088 php8ts.dll
01/15/2023 11:51 AM 280,064 phpdbg.exe
01/15/2023 11:51 AM 30,888 readme-redist-bins.txt
01/15/2023 11:51 AM 5,364 README.md
01/15/2023 11:51 AM 2,285 snapshot.txt
The following files and folders are important to note:
EXT Folder
The ext folder includes all modules provided with PHP. Modules provided additional features which can be added to PHP by enabling them through config files.
PHP.INI* Files
Multiple sample config files are provided with PHP. We will use the config file to manipulate configuration settings as well as enabled various features.
Note: Please make a copy of the file php.ini-development and rename it to php.ini. This will be used later.
PHP.exe
This is a command line executable of PHP used to run command line scripts.
Add PHP to Windows Path
There is one additional step you will need to complete to ensure that all PHP modules will correctly work. For example, if you are going to enable the PHP CURL module, used with WordPress installs, then you need to add the PHP installation folder to the Windows path.
Edit the system environment variables by going to Settings and type env in the search box and open the “Edit the system” option. Click on the Environment Variables button and update the Path variable and add the PHP folder path.
Using my folder path, the setting will look like the following:
Once you have added the path. Save all changes.
Setup PHP FastCGI
Apache server on Windows can load PHP as a module. Nginx on the other hand does not directly load PHP as a module but uses the FastCGI mechanism to support web pages with PHP code.
Create PHP FastCGI Script
Create a new file, php-fcgi.bat in and save it to the folder C:\apps\lang\php\php-fcgi.bat.
Add the following content to php-fcgi.bat and save.
@ECHO OFF
ECHO Starting PHP FastCGI...
set PATH=C:\apps\lang\php;%PATH% # I have already added PHP to the path so this line is optional.
start C:\apps\lang\php\php-cgi.exe -b 127.0.0.1:9123
Run the script from the command line.
C:\apps\nginx>start nginx.exe
This will start PHP fast CGI process in a new command prompt window.
Create PHP Test File
With the changes in place, let’s create a PHP test file.
Open a text editor and copy the following text to it.
In this file I am using a built in PHP funtion phpinfo, which prints PHP configuration as HTML text.
Save this file to the location C:\apps\nginx\html and name it index.php.
Testing Complete Nginx & PHP Install
Now that both Apache and PHP have been installed and configured, to test the setup by first making a change to Nginx webserver configuration file.
Open the file nginx.conf located at C:\apps\nginx\conf\nginx.conf and either add the following lines to the default server block or uncomment the existing PHP location block while updating the PHP port we setup in the script.
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9123;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
After making the change above, start (or restart Nginx server) for the settings to take effect.
Once the server is up and running, then go to the browser and enter the url, http://localhost/index.php.
If everything is configured correctly a web page similar to the one below display PHP configuration will be shown.
This completes Nginx, PHP setup and configuration on computers running Windows 10, 11 or Windows Server.
Bonus Section
In this section, I will review some useful configuration tips.
Download All Configuration and Setup Files Used in this Post
You can download the complete set of configuration, executable scripts and utilities discussed and used in this tutorial from our website. Click on this link to download all tutorial files.
How to Start Nginx From Command Prompt
Go to the Nginx install folder. Let’s assume it is installed at C:\apps\nginx, and run the following command.
C:\apps\nginx>start nginx.exe
How to Stop Nginx on Windows from Command Prompt
You can use the -s signal options with either quit or stop command.
C:\apps\nginx>nginx.exe -s stop
If the Nginx webserver is not running then you will see the following message.
C:\apps\nginx>nginx.exe -s quit
nginx: [error] CreateFile() "C:\apps\nginx/logs/nginx.pid" failed (2: The system cannot find the file specified)
This just shows that the Nginx webserver is currently not running.
How to Install SSL Certification on Nginx
To install or setup a SSL certificate with Nginx you need to modify the server block.
The default nginx.conf file has a server block setup that is listening on port 80. Make the following changes to the existing server block or copy it to a new server block.
Here is an example of a server block set up to listen to incoming SSL requests. This configuration also supports PHP through FastCGI.
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name localhost;
ssl_certificate C:/apps/nginx/ssl-certs/nginx.crt;
ssl_trusted_certificate C:/apps/nginx/ssl-certs/nginx.crt;
ssl_certificate_key C:/apps/nginx/ssl-certs/nginx.key;
location / {
root html;
index index.html index.htm;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9123;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
You can download sample certs from our website by clicking here.
How to Setup Nginx Virtual Hosts
For Nginx to serve multiple domains or hosts you need to create different server blocks, each one serving a different domain. To add an additional virtual host add the following code to existing nginx.conf file.
server {
listen 80;
server_name example.com;
location / {
root html;
index index.html index.htm;
}
}
This configuration adds the ability to serve domain example.com by Nginx.
Note: After making changes restart the Nginx webserver for it to pickup changes.
Hiding Command Prompt Windows For Background Tasks
I don’t like command prompt windows running programs but just hanging in the background. If you are like me then you probably would like to hide the PHP FastCGI program window.
There is a utility HideWindowsConsole that you can download my our website and use it to run PHP FastCGI.
Make the following changes to your PHP FastCGI script to start the script with a hidden window.
@ECHO OFF
ECHO Starting PHP FastCGI...
set PATH=C:\apps\php;%PATH%
C:\apps\misc\HideWindowsConsole.exe C:\apps\php\php-cgi.exe -b 127.0.0.1:9123
Conclusion
In this post, I went over details on setting up Nginx on the Windows operating system. On my Nginx web server page, you will find many more tutorials on Nginx.
NGINX can interface with PHP on Windows via a FastCGI daemon, which ships with PHP: php-cgi.exe. You need to run php-cgi.exe -b 127.0.0.1: and use fastcgi_pass 127.0.0.1:; in the NGINX configuration file. After being launched, php-cgi.exe will keep listening for connections in a command prompt window. To hide that window, use the tiny utility RunHiddenConsole
First
- Download nginx, choose stable version.
- Download PHP, choose non stable version.
Second
- Extract nginx to «C:\nginx»
- Extract php to «C:\php»
- Create folder «www» in your «C» system , «C:\www»
Third
- Edit your nginx.conf at «C:\nginx\conf\nginx.conf»
-
Change root
root c:/www; -
Save nginx.conf
-
Open yout php folder, find php-ini-development
-
Edit your php-ini-development, like down below.
extension_dir = "ext" enable_dl = On cgi.force_redirect = 1 fastcgi.impersonate = 1 cgi.rfc2616_headers = 1 extension=php_gd2.dll extension=php_mbstring.dll extension=php_exif.dll extension=php_mysql.dll extension=php_mysqli.dll extension=php_pdo_mysql.dll date.timezone = "Asia/Jakarta" -
Save it.
-
Open your nginx.conf again
-
Uncoment on php configuration and change to this
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9999 location ~ \.php$ { fastcgi_pass 127.0.0.1:9999; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } -
Save nginx.conf again.
Fourth
- Set Php path
- Open your environment variable
Create nginx start, stop & restart .bat
- Download RunHiddenConsole first, and move RunHiddenConsole.exe to «C:\».
-
Create file «nginx-start.bat», edit file with down below, make your php-cgi.exe port same as in nginx.conf
@ECHO OFF ECHO Starting PHP FastCGI... C:\RunHiddenConsole.exe C:\php8\php-cgi.exe -b 127.0.0.1:9999 ECHO Starting NGINX start nginx.exe popd EXIT /b -
Create file «nginx-stop.bat», edit with this
@ECHO OFF taskkill /f /IM nginx.exe taskkill /f /IM php-cgi.exe EXIT /b -
Create file «nginx-restart.bat»
@ECHO OFF call nginx-stop.bat call nginx-start.bat EXIT /b
Test
- Doble click on «nginx-start.bat»
- Open your browser if every thing work you can see like this
- Create folder like «test-php» in «C:\www»
-
Create file «index.php»
<?php phpinfo(); ?> -
Open your browser and go to «localhost/test-php»
-
If every thing ok you can see
-
At the end , nginx php now working.
Notes:
Sometimes , nginx & php cannot working properly if your run with nginx-start.bat
so you need to run php manually
open your terminal, run your php «php-cgi -b 127.0.0.1:9999»
and now your nginx & php work properly
