Install¶
Most Linux distributions and BSD variants have NGINX in the usual package repositories and they can be installed via whatever method is normally used to install software ( apt on Debian, emerge on Gentoo, ports on FreeBSD, etc).
Be aware that these packages are often somewhat out-of-date. If you want the latest features and bugfixes, it’s recommended to build from source or use packages directly from nginx.org.
Official Red Hat/CentOS packages¶
To add NGINX yum repository, create a file named /etc/yum.repos.d/nginx.repo and paste one of the configurations below:
Due to differences between how CentOS, RHEL, and Scientific Linux populate the $releasever variable, it is necessary to manually replace $releasever with either 5 (for 5.x) or 6 (for 6.x), depending upon your OS version.
Official Debian/Ubuntu packages¶
The available NGINX Ubuntu release support is listed at this distribution page. For a mapping of Ubuntu versions to release names, please visit the Official Ubuntu Releases page.
Append the appropriate stanza to /etc/apt/sources.list . If there is concern about persistence of repository additions (i.e. DigitalOcean Droplets), the appropriate stanza may instead be added to a different list file under /etc/apt/sources.list.d/ , such as /etc/apt/sources.list.d/nginx.list .
e.g. Ubuntu 20.04 (Focal Fossa):
To install the packages, execute in your shell:
If a W: GPG error: https://nginx.org/packages/ubuntu focal InRelease: The following signatures couldn’t be verified because the public key is not available: NO_PUBKEY $key is encountered during the NGINX repository update, execute the following:
You have now nginx installed on your server but not ready to serve web pages. you have to start the nginx. You can do this by using this command:
Append the appropriate stanza to /etc/apt/sources.list .
Ubuntu PPA¶
This PPA is maintained by volunteers and is not distributed by nginx.org. It has some additional compiled-in modules and may be more fitting for your environment.
You can get the latest stable version of NGINX from the NGINX PPA on Launchpad: You will need to have root privileges to perform the following commands.
For Ubuntu 20.04 and newer:
If you get an error about add-apt-repository not existing, you will want to install python-software-properties . For other Debian/Ubuntu based distributions, you can try the lucid variant of the PPA which is the most likely to work on older package sets:
Official Win32 Binaries¶
As of NGINX 0.8.50, NGINX is now available as an official Windows binary.
For problems look in c:nginxlogserror.log or in EventLog.
In addition, Kevin Worthington maintains earlier Windows builds of the development branch.
Source Releases¶
There are currently two versions of NGINX available: stable (1.20.x) , mainline (1.21.x) . The mainline branch gets new features and bugfixes sooner but might introduce new bugs as well. Critical bugfixes are backported to the stable branch.
In general, the stable release is recommended, but the mainline release is typically quite stable as well. See the FAQ .
How to Install Nginx, PHP, and MySQL on Windows 11
Installing a web server using a distribution package like XAMPP, and WinNMP are probably the easiest solution to make your localhost server works. But what if we wanted to make it from scratch? and avoid duplication whenever we install a composer, laravel and other development kit. Also, you’re free to upgrade them whenever a new version comes out.
The guide has been updated to run on the latest Windows 11, it should work on Windows 10, 8 and 7.
Table of Contents
If you’re not running the latest Windows 11, you need to install the version of VC_Redist you can get it from at https://support.microsoft.com/en-us/topic/the-latest-supported-visual-c-downloads-2647da03-1eea-4433-9aff-95f26a218cc0, then look for Visual Studio 2015, 2017 and 2019, then download your either vc_redist.x86.exe or vc_redist.x64.exe. If you don’t have that, you’ll get this error message when using the PHP.
or if you have a lower version of VC_Redist installed, you’ll get this error.
That’s for installing the prerequisite. Let’s now install the latest version of NGINX 1.19.6 + PHP 8.0+ MySQL 8.0.22.
Nginx
To install nginx, you need to download it from http://nginx.org/en/download.html. Select the Mainline version zip files. Currently, it’s nginx/Windows-1.19.6.
Once downloaded, create a folder in your computer. You may follow our naming convention or create your own. In our case we create a folder at C:\WebServer .
After created a folder, create again a folder for our Nginx. It should be C:\WebServer\nginx .
Unzip the downloaded nginx-1.19.6.zip at C:\WebServer\nginx folder.
It’s all good for now, we can discuss later how we activate it.
To get binaries installation for PHP on Windows, you can grab it at https://windows.php.net/download/.
Then at the PHP 8.0, download the VS16 x64 Non Thread Safe zip file, so we can use it alongside with our Nginx and MySQL.
If you want to use the older version, PHP 7.4, download the VC15 x64 Non Thread Safe zip file.
Once downloaded, create a folder C:\WebServer\php and extract the file at C:\WebServer\php
MySQL
There are two ways to install MySQL by its installer or via zip. Both has pros and cons. Installing using its installer is easier and will not allow you to set things. Advantage of using the zipped version is its portability, you can easily transfer everything in a new computer.
Using Installer
To install MySql, you can downloaded the installer version at https://dev.mysql.com/downloads/installer/. Pick the mysql-installer-web-community-8.0.23.0.msi.
Run the installation, and when you are asked to what to install. Just install MySQL Server, other module is not needed.
You’ll then asked to set your MySQL password. Just fill up the form and when finish, the MySQL will run automatically.
We also suggest to start MySQL when windows start.
Using Zipped
You can download the zipped version at https://dev.mysql.com/downloads/mysql/. Scroll down and look for Windows (x86, 32 & 64-bit), ZIP Archive.
Once done, create a folder and unzipped the downloaded file at C:/WebServer/mysql .
Launch a command prompt as a Administrator and we can now initialize the MySQL setup.
You can then run the mysql using this command. Make sure to Allow Access when it asked for permission.
You need to open a new command prompt window to login to our MySQL. (Do not close the previous command prompt or else you’ll get an error saying ‘error 2003 (HYOO): Can’t connect to MySQL server on ‘localhost’ (10061))
In MySQL 8.0 and above, the default authentication plugin is caching_sha2_password which not allow you to connect to the mysql using the default native login in php. Most users will get this error message saying “Connection failed: The server requested authentication method unknown to the client”. To enable it back to native, we have to set your root password with mysql_native_password.
Add them to PATH environment
In order for us to call nginx, php and MySQL straight from the command line or Windows Powershell without going to its directory, this is needed for other module like Laravel and Composer. We need to add it in the PATH directory.
In the Search bar (Cortana) in your Windows taskbar, just search Edit the system environment variables.
At the bottom, Click the Environment Variables.
Then, you can either add both on User Variables for YOUR_USERNAME or System variables path. Look for Path then click Edit.
Now, we have to add these directories. If you use the installer for MySQL, no need to add the C:\WebServer\mysql\bin .
Once done, click OK.
To see if it works, try running these commands using the Windows Powershell or Command Prompt.
You should get these output.
You cannot call yet the nginx -t at the command prompt, because this will cause an error which are looking for files on its relative directory. We can discuss this later on how to get rid of this using a batch command file.
Wrap up
Now that we already added them to path. Let’s do some finishing touch.
To make PHP communicate with our MySQL. At C:\WebServer\php , we need to add the module in our PHP. First, rename the php.ini-production to php.ini file
After renaming it, open the php.ini file, search for extension=/path/to/extension/mysqli.so and uncomment the line by removing the semi-colon “;”, then change its value to our mysqli dll (Unfortunately, we need to manually add the exact path of the dll because it is causing error when just using the default extension name).
You can then also enable other module extension (DLLs) that are needed for your program. Like the following that are needed for WordPress.
We also need to edit our loadable extensions module to avoid PHP Warning for our MySQL. Search and find the ;extension_dir = «ext» then uncomment and replace the value with extension_dir = «c:\WebServer\php\ext\» . (Credits to Mohamed for this tip)
In the next step, we will be making a batch file. But there is a problem, running nginx and php-cgi in the batch command line will not allow us to execute the next line of code. Simply because the program is not yet closed for it to proceed on to the next line.
In order for us to run each lines of code of our batch file, we need to hide the command prompt windows by using RunHiddenConsole, you can download this at their official website (https://redmine.lighttpd.net/attachments/660/RunHiddenConsole.zip).
At C:\WebServer\nginx , unzip the RunHiddenConsole.zip.
Then still at C:\WebServer\nginx , we need to create a batch file called C:\WebServer\nginx\myserver.bat . This is where we will start and stop our nginx and php-cgi by using a single command line. Add the following code. (Thank you to Mohamed for enhancing this code).
After that, you can now use these commands for starting and stopping your server at the Command Prompt.
- myserver start – It will start Nginx, and PHP
- myserver stop – It will stop all instances of Nginx and PHP
But before running the commandline above, we have to edit some blocks on our C:/WebServer/nginx/conf/nginx.conf .
First we have to make sure index.php is been recognized by our nginx. find the location / <> block and change it with the following:
Next is we have to make sure nginx know where to run the php files. Find and uncomment the block that says location
.php$ <>, the one that says “pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000”. Change it with the following:
Once everything is good. Create a file in C:\WebServer\nginx\html\testing.php . Then write this sample PHP codes with MySQL connection checker (Make sure to fill up your MySQL login, the default username is root).
Then at the command prompt. Let’s start our server. (Do not forget to Allow Access when Windows Defender Firewall is asking for permission.)
How to Install and Run the Nginx Server on Windows
Nginx is a web server that is very popular with Linux and BSD systems. It can also be installed on Windows 10. However, there are a few performance limitations in Windows that have not been mitigated so far, but the developers will address these problems in a future release. To install and run Nginx successfully on Windows, follow the steps below.
Download the Nginx Server
There are many download versions of Nginx for Windows, and Nginx recommends using the “mainline version.” However, you will not find any issues if you download its most recent stable version for Windows.
Select the version you want and download its zip file to your PC.
As a first step, you need to extract the new folder. You can use 7-zip, WinRAR or any other popular compression software.
After extracting the file contents in the original folder, you have to move the entire folder that came with the built-in download copy into the “Program Files.” We can either move or cut-paste this extracted folder.
We will run Nginx from this location as a default web service program.
Installing Nginx
To install and run Nginx, select and double-click the Nginx.exe file. It has now been activated for further use. You may run into a Windows Defender block screen while running the Nginx server, which has to be allowed by you.
In the next step, you need to verify whether the installation has been successful. For this, go to your default browser and type localhost . Microsoft Edge is the browser used in the below example. 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.
To stop Nginx, you can end it from the Task Manager window.
Running Nginx on Your Windows PC
To run Nginx, you have to use Internet Information Services (IIS), which is a Microsoft web server that serves requested HTML pages or files. 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.”
It will take a while for IIS to be enabled on your computer as the changes are applied.
You can open IIS Manager directly from the Start menu. Always open it in Administrator mode.
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.
It is helpful to change the physical path of this root to a more desirable folder. I created a new “Work” folder in C:\ and changed the physical path to “C:\Work.” 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.
After this, go to the Nginx folder that you renamed in the Program files. Click “Conf” and select “nginx.conf.” This file can be edited using the Notepad++ text editor, but you can use any other editor such as Atom or Visual Studio Code.
In Notepad++, find the location of the root and change it from the default html.
As shown here, change the root to the edited physical path which we discussed above.
You can edit the index.html file in the root folder in a separate tab. Change the text to what you want the web server to display on the screen.
Exit the Nginx.exe program using “End Task.” Open and run the “nginx.exe” file in Admin mode.
Type localhost in a browser window. The Nginx web server will highlight the edits you made.
Example Application of Nginx in Windows
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.
Go back to the “nginx.conf” file shared in the previous section. Instead of “localhost,” you need a domain name for the server to access. “index.html” is a command used to point to any static html page.
In the next step, 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.
Save the file and run the “Nginx.exe” program in Admin mode. For this login page to look nice to the end user, you should have previously configured the web server in an IDE program like Eclipse.
Frequently Asked Questions
1. What are the basic commands in operating Nginx for Windows 10?
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 |
2. What is the role of IIS Webserver in Nginx applications in Windows?
IIS is Microsoft’s native web server which supports HTTP, HTTPS, SMTP, and other protocols, and is not enabled in Windows as default. When Nginx is installed in Windows, it handles the live traffic based on changes made in nginx.conf files. For this, Nginx has to connect internally to an enabled IIS and then cache its response for any future requests.
Nginx’s biggest strength is that it is used at the front end before high load dynamic sites. Imagine tens of thousands of your website users downloading an important video file from IIS at the same time. It can become painfully slow. if you have a very powerful front-end server like Nginx handling the traffic instead, the request is processed faster. Check the “running Nginx on Windows PC” section for more details on IIS webserver’s role.
3.How Does Nginx Run in Windows?
Nginx supports multiple applications in Windows, such as web server, load balancer, mail proxy, and more. To run them in Windows, all desired changes are affected from various strings modified in the “nginx.conf” file in the Windows installation folder. To know more about Nginx commands, including the documentation, visit this link.
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.
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.
1234ru / nginx-php-win.md
Скачиваем отсюда https://nginx.org/ru/download.html и распаковываем куда-нибудь.
Дальше читаем тут https://nginx.org/ru/docs/windows.html ВНИМАНИЕ: команду start nginx обязательно даем прямо из каталога, в котором лежит nginx.exe, в противном случае при дальнейшей работе будут ошибки (все пути в конфигурации прописаны как относительные, только поменяв их все, можно запускать откуда угодно). Вообще рекомендуется держать консоль открытой в этом каталоге до самого конца выполнения инструкций, однако для работы nginx это необязательно — если её закрыть, он продолжит работать.
Открываем http://localhost/ — должно заработать.
Скачиваем с https://windows.php.net/download (ZIP-архив Non Thread Safe x64), замечаем номер в «VC(число)» — понадобится на следующем шаге. Прописываем каталог в PATH.
Открываем командную строку, запускаем php -v . Должно выскочить окно с надписью «The program can’t start because VCRUNTIME140.dll». Если запуск прошел без ошибок, пропускаем следующий пункт.
Ищем на странице загрузки из п.1 в левой колонке ссылку на VC нужного номера. Скачиваем x64.exe, устанавливаем. После этого возвращаемся на предыдущий пункт. На этот раз команда должна показать версию php.
Конфигурация локального сайта в nginx
Выбираем локальное имя хоста (как localhost , только какое-то другое, например, mysite ) и каталог, где будут находиться его файлы (например, D:\sites\mysite ).
В конец файла (каталог nginx)/nginx.conf перед последней закрывающей скобкой добавляем раздел:
В консоли, находясь в каталоге nginx.exe, даем команду nginx -s reload , чтобы nginx перечитал конфигурацию.
Открываем файл C:\Windows\System32\Drivers\etc\hosts , добавляем строчку
Файл защищен системой ото всех пользователей, кроме администратора, поэтому перед записью понадобится открыть его свойства и дать там нужные права и потом вернуть, как было.
Открываем в браузере ссылку http://mysite/ (обязательно с http:// , иначе браузер станет отправлять в поисковые системы). Должна отобразиться страница 404 от nginx.
Налаживание взаимодействия nginx и PHP
В раздел server конфигурации добавляем такие строки:
( 9123 — номер порта, можно выбрать какой-нибудь другой)
Из консоли даем команду nginx -s reload .
В консоли переходим в каталог, куда распакован PHP. Даем команду
Закрывать окно консоли нельзя, иначе интерпретатор PHP перестанет работать.
Можно прописать путь к каталогу PHP в системной переменной PATH и запускать его без указания полного пути.
Создаем файл D:\sites\mysite\test.php со следующим содержимым:
Открываем http://mysite/test.php — текст должен отображаться.
PHP: ini-файл и модули расширений
Вышеуказанные процедуры позволяют успешно запустить и использовать PHP, однако он будет «голым» — без расширений (в т.ч. таких необходимых, как mysqli , mbstring и др.) и без настроек, т.к. он не прочитает ни одного ini-файла.
PHP может автоматически загрузить файл php.ini из нескольких каталогов. Первое место, где он станет его искать — рядом с php.exe . В пакете есть файл php.ini-development . Нужно создать рядом его копию с именем php.ini , открыть и внести следующие изменения:
Раскомментировать строку extension_dir = «ext» — в результате PHP станет искать модули расширений в подкаталоге ext рядом с php.exe
(относительный путь интерпретируется именно от exe-, а не от самого ini-файла)
Проверяем, подключился ли файл, с помощью команды php —ini . Результат должен быть примерно следующим:
Вторая строчка говорит о том, что ini-файл успешно загрузился.
На первую строчку (про С:\Windows) внимания обращать не следует, т.к. ini-файла по указанном адресу нет.
Найти нужные расширения и раскомментировать строки, где они подключаются. Например, extension=mysqli и т.д.
Все расширения перечислены рядом, и найти нужные среди них несложно. Рекомендуется включить следующие:
- curl
- fileinfo
- gd2
- mbstring
- exif
- mysqli
- soap
Просмотреть список подключенных расширений можно, дав команду php -m . Непустой изначально список после вышеописанной манипуляции пополнится.
PHP загружает расширения при запуске exe-файла интерпретатора. Если нужно подключить новое, следует остановить php-cgi.exe (или php.exe соответственно) и запустить его заново.
Чтобы установить связь между PHP и MySQL, не требуется никаких специальных действий, кроме собственно создания соединения (разумеется, должен быть включен соответствующий модуль, например, mysqli ).
Проверить соединение можно так:
Об установке и минимальной настройке MySQL под Windows см. здесь.
Неудобства работы под Windows
в путях файловой системы используется обратный слэш ( \ ), а не прямой ( / ) — типа D:\sites\mysite\. вместо /sites/mysite/. , что влияет, в частности, на содержимое констант __DIR__ и __FILE__ ;
как следствие, весь код, рассчитанный на разбор пути по слэшу, перестаёт работать
невозможно установить русскую локаль с UTF-8: setlocale(LC_ALL, ‘rus’) всегда приводит к использованию windows-1251, и изменить это никак не получается