nginx php fpm mac os
Настройка окружения для web-разработки на Mac OS X
согласившись с лицензионным соглашением.
Установка Homebrew
Открываем терминал (вместо стандартного я использую ITerm2) и запускаем установку командой:
После установки обновляемся, проверяем все ли в порядке:
В качестве сервера баз данных я решил использовать MariaDB.
Cтавим MariaDB:
Выпоним первоначальную настройку сервера:
и проверяем подключение:
Займемся web сервером nginx:
Настройка nginx и создание структуры директорий.
Для виртуальных хостов я использую следующую структуру (вы можете использовать другую, удобную вам но не забудьте исправить пути в конфигах!):
Конфигурационные файлы вирутальных хостов.
Я использую следующую схему:
После установки nginx, в директории /usr/local/etc/nginx/ имеется стандартный конфигурационный файл nginx.conf. Приведем его к следуюущему виду:
Далее пишем конфигурацию виртуального хоста в директории /usr/local/etc/nginx/sites-available/
Создаем символьную ссылку:
Установка PHP
Если используете zsh то:
либо (в зависимости от того какой используется шел)
Версии должны быть одинаковыми!
Далее создадим файл index.php для проверки:
В адресной строке браузера набираем localhost и смотрим результат. Чтобы сервисы автоматически запускались после перезагрузки:
Вот вроде бы и все. Если возникнут вопросы, пишите в комментариях либо через форму обратной связи на странице контактов.
Установка окружения для разработки PHP на macOS и Linux
Настройка окружения PHP-разработчика в macOS
Пакетный менеджер
Скачивать и устанавливать весь требуемый софт мы будем с помощью пакетного менеджера Homebrew.
Пакетный менеджер — это инструмент, который значительно облегчает процесс установки любых программ. С Homebrew установка программы на компьютер сводится буквально к одной команде в терминале.
Но сам Homebrew тоже требуется установить, так как по умолчанию он не входит в состав операционной системы.
Понятная инструкция по его установке есть на главной странице этой программы. Выполните её и переходите к следующему шагу.
Установка PHP
Начнём с установки PHP-интерпретатора.
Все последующие команды выполняются через терминал.
Установить интерпретатор можно через одну простую команду:
Проверим, что всё установилось корректно:
Установка веб-сервера
PHP — это язык программирования, на котором можно создавать современные сайты. Обработкой запросов пользователей и отдачей им запрошенных страниц занимаются специальные программы — веб-сервера.
PHP работает в тесной связке с веб-сервером, так как именно последний обращается к нему и, в конечном счёте запускает наши сценарии. В общем, без веб-сервера нам никак не обойтись.
Поднять веб-сервер можно с помощью плагинов для редактора или настроить веб-сервер самостоятельно. Рассмотрим оба варианта.
Использование веб-сервера из редактора
Современные редакторы могут самостоятельно запускать сервер. В VS Code это можно сделать через плагин PHP Server, а в PHP Storm через — PHP Debug Server. По ссылкам есть инструкция с настройками. Для того, чтобы сервер стартовал, нужно чтобы локально был установлен php интерпретатор.
Установка nginx
Рассмотрим как установить веб-сервер самостоятельно.
Установим последнюю версию nginx:
Запускаем nginx, чтобы он работал в фоне и обслуживал наши запросы:
Проверяем, что всё установилось корректно, и nginx успешно работает на нашем компьютере:
откройте любой браузер и введите в адресной строке следующий URL:
в ответ вы должны увидеть страницу с текстом «Welcome to nginx!»
Интеграция PHP и веб-сервера
На этом шаге мы «подружим» PHP-интерпретатор и nginx, чтобы при запросе веб-страниц с расширением.php автоматически выполнялся php-сценарий и мы видели результат его работы в браузере.
Откройте конфигурационный файл nginx:
Добавим в конец документа перед закрывающей скобкой от блока http следующий код:
USERNAME нужно будет в двух местах заменить на имя вашего пользователя
Разрешим nginx читать содержимое нашего проекта
(*)Поменяйте USER на имя вашего пользователя и yeticave на папку вашего проекта
Для того, чтобы изменения применились на 80 порт, нужно перезагрузить сервер с доступом администратора командой:
Установка xdebug
Установить xdebug можно простой командой:
Проверка работы
Базовая настройка окружения закончена. Осталось проверить, что мы всё сделали правильно.
Создадим тестовый PHP-сценарий со следующим содержимым:
Установка MySQL в macOS
Актуальную версию MySQL для macOS можно загрузить с официальной страницы. Для удобства установки рекомендуется загружать DMG Archive. В этом случае процесс установки будет выполняться с помощью стандартного инсталлятора.
Рисунок 1. Окно инсталлятора
Рисунок 2. Выбор компонент для установки
Рисунок 3. Автоматически сформированный пароль
Рисунок 4. Окно System Preferences
Рисунок 5. Аплет запуска MySQL
Чтобы протестировать соединение с MySQL и получить возможность выполнять базовые задачи, вам потребуется фирменная утилита от Oracle — MySQL Workbench. Установка утилиты выполняется стандартным для macOS способом: запускаем загруженный DMG и в окне инсталлятора перетаскиваем иконку MySQL Workbench в папку Application.
Для тестирования корректности установки MySQL запустим MySQL Workbench и попробуем установить соединение.
Рисунок 6. Главное окно MySQL Workbench
Рисунок 7. Соединение с MySQL установлено
Установка на Linux
Настроить рабочее окружение для разработки на PHP в Linux возможно несколькими способами. Рассмотрим один из наиболее быстрых способов: настройка связки PHP плюс nginx.
Запустите приложение «Терминал». Ярлык на запуск доступен в менеджере приложений.
Установка PHP
Последним компонентом в настройке рабочего окружения станет PHP.
В окне терминала введите команду для установки php-fpm из репозитория.
Настройка xdebug
Сохраняем изменения ctrl + o и закрываем редактор nano ctrl + x.
How to setup Nginx and PHP7.1 with FPM on Mac OS X without crying
If you are new to http servers on your local machine, this article would make setting up nginx pretty easy for you even if you don’t understand most of the stuff. If you use LAMP or WAMP or any of that, you might want to go read up on setting up nginx for your OS before coming right here. The nginx configurations would be the same. Just the folders to find the nginx.config file for nginx may change from OS to OS. Yes, this should work for non Mac users as well.
To make this article pretty useful to you, I’d skip a lot of stuff that are not the focus (stuff that there are probably like 1,000 articles on already). I’d speed through a lot of this. I use High Sierra on my Mac (I used Sierra before) so I cannot guarantee what would happen for other versions of macOS X. If you are following and anything is missing, do not fret. Just Google how to install it and then continue with this setup.
If you already have Nginx and PHP7.1 installed, you can skip to the installation section and head straight to configuration.
INSTALLATION
We are going to use Homebrew for all our installations. It makes life easy and it is pretty straightforward. Click here to read about it or just install right away.
When you are done, ensure homebrew’s environment is setup correctly.
Next we’re going to install a launchctl wrapper that will stop, start, and restart any service we install with brew.
Let’s install php7.1 with fpm and display the version after installation.
Start PHP right away.
We would not have to setup much for PHP7.1 with FPM because it comes pretty configured right out of the box. Let’s just get nginx and get the party going.
We are done with installations for now, time for configurations. Nginx should be running on port 8080 if you also have apache installed and running. Either way, you should see which port it is running on after installation, so you can quickly visit http://localhost:8080 to see the default nginx homepage (use the port displayed in your terminal after setup instead, if it is not 8080).
THE CONFIGURATION
Don’t forget to add index.php to the index list so that nginx can automatically load that file when it serves your site.
The next thing is to setup how our php files are proxied for execution. Edit your block to match the following.
If you are using multiple configuration files (all stored in /sites-available ), you would have to adjust them one by one as well. You can store this setup block above in a separate file and include it in all of them if they all use the same root folder.
Time to test our beautiful setup. Create an info.php file in /usr/local/var/www folder and put any php code of your choice that should output stuff (I echoed phpinfo() ). Go to http://localhost:8080/info.php and it should display just fine (use the port displayed in your terminal after setup if it is not 8080).
Now buddy, go enjoy your nginx and cry no more.
NGINX is a free, open-source, high-performance HTTP server known for its high performance, stability, rich feature set, simple configuration, and low resource consumption. If you want to see how nginx performs in handling requests and heavy usage when compared to apache, read Web server performance comparison. If you would like to understand better about the individual strengths of nginx and apache, checkout this article on Digital Ocean.
dtomasi / default
Install NGINX with PHP7-FPM on Mac OS X with Homebrew
Install Commandline Tools
Install brew services
brew tap homebrew/services
Install bash completion (Optional)
brew install bash-completion
Update Brew and Packages if allready installed
brew update && brew upgrade
Add following lines
Start, Stop and Restart
sudo nano /usr/local/etc/php/7.0/php-fpm.d/www.conf
sudo brew services start php70
show running processes
Output should look like this
sudo brew services stop nginx
Create missing directories
Start and Test Nginx
Create a folder for our SSL certificates and private keys:
Generate 4096 bit RSA keys and the self-sign the certificates in one command:
Setup example virtual hosts
These are working presets. But you need to edit Document-Root
Activate Virtual Hosts
Create info.php for testing echo » /path/to/your/document/root
server < |
listen 80; |
server_name localhost; |
root /Users/YOUR_USERNAME/Sites; |
access_log /Library/Logs/default.access.log main; |
location / < |
include /usr/local/etc/nginx/conf.d/php-fpm; |
> |
location = /info < |
allow 127.0.0.1; |
deny all; |
rewrite (.*) /.info.php; |
> |
error_page 404 /404.html; |
error_page 403 /403.html; |
> |
server < |
listen 443; |
server_name localhost; |
root /Users/YOUR_USERNAME/Sites; |
access_log /Library/Logs/default-ssl.access.log main; |
ssl on; |
ssl_certificate ssl/localhost.crt; |
ssl_certificate_key ssl/localhost.key; |
ssl_session_timeout 5m; |
ssl_protocols SSLv2 SSLv3 TLSv1; |
ssl_ciphers HIGH:!aNULL:!MD5; |
ssl_prefer_server_ciphers on; |
location / < |
include /usr/local/etc/nginx/conf.d/php-fpm; |
> |
location = /info < |
allow 127.0.0.1; |
deny all; |
rewrite (.*) /.info.php; |
> |
error_page 404 /404.html; |
error_page 403 /403.html; |
> |
This comment has been minimized.
Copy link Quote reply
baumannsven commented Aug 2, 2016
By section dnsmasq => configure.
Before download the dev in /etc/resolver, must be create the resolver directory.
This comment has been minimized.
Copy link Quote reply
baumannsven commented Aug 3, 2016 •
By sites configuration default in line 15 and default-ssl in line 25 replace with:
rewrite (.*) /info.php;
This comment has been minimized.
Copy link Quote reply
baumannsven commented Aug 3, 2016
Replace the correctly curl url for:
This comment has been minimized.
Copy link Quote reply
baumannsven commented Aug 3, 2016
After download site configuration, download php-fpm configuration.
This comment has been minimized.
Copy link Quote reply
raymondjplante commented Jan 2, 2017
This comment has been minimized.
Copy link Quote reply
ghost commented Feb 14, 2017
I get curl: (7) Failed to connect to 127.0.0.1 port 8080: Connection refused and curl: (7) Failed to connect to localhost port 80: Connection refused
Help! Everything else went fine with no trouble, I just can’t view anything.
This comment has been minimized.
Copy link Quote reply
johnwilson commented Mar 22, 2017
@the-interactive-company you might have manually create the /Library/Logs/nginx/ directory
This comment has been minimized.
Copy link Quote reply
chaeMil commented Mar 22, 2017
i keep getting bad gateway error when trying to run php files. Im on El Capitan.
This comment has been minimized.
Copy link Quote reply
datadimension commented Mar 25, 2017
This comment has been minimized.
Copy link Quote reply
njsubedi commented Apr 4, 2017
@chaeMil your php-fpm instance is not running.
This comment has been minimized.
Copy link Quote reply
tobecwb commented Jun 1, 2017
Some corrections to make this thing works:
on PHP-FPM, in Configure ( sudo nano /usr/loca/etc/php7.0/php-fpm.d/www.conf ), use:
(don’t need the YOUR_GROUP || staff)
remove the line error_log /Library/Logs/nginx/error.log debug;
inside http section, insert/update the following lines:
remove sendfile on;
then, the php-fpm must be configured.
create a file in /usr/local/etc/nginx/conf.d/php-fpm with the following content:
and finally, configure the virtual hosts.
I don’t remember if this is all that I changed, but worked fine after this.
This comment has been minimized.
Copy link Quote reply
birchcode commented Nov 24, 2017
Thank you for wasting my time with this buggy shit.
This comment has been minimized.
Copy link Quote reply
apedicdev commented Nov 24, 2017
@birchcode you may write yours
This comment has been minimized.
Copy link Quote reply
fsebbah commented Feb 20, 2018 •
@tobecwb : your config are correct just in the nginx.conf at the header it’s important to add
user YOUR_NAME YOUR_GROUP;
without this you have an 403 error
Here you find a good config nginx website
This comment has been minimized.
Copy link Quote reply
thanhoangxuannghiep commented Apr 22, 2018
I cannot tap to homebrew/dupes. When I run command «brew tap homebrew/dupes». I got this message: «Error: homebrew/dupes was deprecated. This tap is now empty as all its formulae were migrated». How’s about this issue?
This comment has been minimized.
Copy link Quote reply
bindzus commented Apr 26, 2018
@thanhoangxuannghiep I don’t think you need homebrew/dupes anymore, it looks like everything you need is available from Homebrew core.
This comment has been minimized.
Copy link Quote reply
pooyagolchian commented Jun 18, 2018
Why php-fpm is not in conf.d folder?
This comment has been minimized.
Copy link Quote reply
maitandat1507 commented Oct 7, 2018
Some corrections to make this thing works:
on PHP-FPM, in Configure ( sudo nano /usr/loca/etc/php7.0/php-fpm.d/www.conf ), use:
(don’t need the YOUR_GROUP || staff)
remove the line error_log /Library/Logs/nginx/error.log debug;
inside http section, insert/update the following lines:
remove sendfile on;
then, the php-fpm must be configured.
create a file in /usr/local/etc/nginx/conf.d/php-fpm with the following content:
and finally, configure the virtual hosts.
I don’t remember if this is all that I changed, but worked fine after this.
Thanks for your php-fpm configuration content! It save my day!
Brew’ing PHP, MySQL & Nginx on Mac OS X
There are many ways to install PHP, MySQL & Nginx on Mac. Here we will be doing it using brew.
Installing PHP 5.4 (with FPM) on Mac OS X
Search for available PHP formulas (formula’s in homebrews are equivalent to packages in aptitude)
It will return long list of php 5.2, 5.3, 5.4 packages. We need 5.4. Tap it using:
If you do not tap homebrew/dupes you will get Error: No available formula for zlib
Before we build PHP 5.4, you may like to exercise options using:
We have built it using:
Adding PHP-FPM to startup routine
Please check exact plist filename in /usr/local/Cellar/php54/
Installing MySQL on Mac OS X
Run following command:
In case you need mysql-workbench, please download it from here. It cannot be installed via brew.
Adding MySQL to startup routine
Please check exact plist filename in /usr/local/Cellar/mysql/
Manual Start/Stop
Start mysql: /usr/local/mysql/support-files/mysql.server start
Stop mysql: /usr/local/mysql/support-files/mysql.server stop
Changes to MySQL Config (optional)
For security
For workbench
Following changes will make it easy to use MySQL WorkBench
Installing Nginx on Mac OS X
Run following command:
Adding Nginx to startup routine
Please check exact plist filename in /usr/local/Cellar/mysql/
Changes to Nginx Config (optional)
By default, Nginx setup expects you to define all virtual hosts in /usr/local/etc/nginx/nginx.conf
Edit default config file and following line to http <..>block
Troubleshooting
Finding default location of config/error files for PHP, MySQL & Nginx
I did not get any error but after getting used to Ubuntu-conventions, I struggled to find where are config/log files and other defaults are present.
3 commands below turned out to be life-saver:
Brew’s list command shows all files/folders created by a package. Once you see output, you will notice, why I was getting lost!
If you come across any other error, feel free to use our support forum. We will try to fix it there.
Share this:
Like this:
15 responses to “Brew’ing PHP, MySQL & Nginx on Mac OS X”
Not so far I have found new cool tool to work with mySQL on mac os x – Valentina Studio. Its free edition can do things more than many commercial tools!!
I very recommend check it. http://www.valentina-db.com/en/valentina-studio-overview
You can install Valentina Studio (FREE) directly from Mac App Store: https://itunes.apple.com/us/app/valentina-studio/id604825918?ls=1&mt=12
Thanks for sharing. I will have a look at it.
Yes of course. But I agree to some people from this discussion http://www.reddit.com/r/webdev/comments/1fxcyd/try_valentina_studio_a_new_free_gui_manager_for/ that Workbench sometimes is awful.
I recommend Sequel Pro, which I find to be by far the best free MySQL-manager for OSX, check it out if you haven’t tried it yet: http://www.sequelpro.com/
Looks like sourceforge mirror from which download in progress timed out. You can try again whole commands.
Such errors should be temporary!
checking for libpng… configure: error: `libpng-config’ not found;
either set the LIBPNG_CFLAGS and LIBPNG_LDFLAGS environment variables,
or pass `–without-png’ to the `configure’ script.
make: *** [setup] Error 1
—————————————————————————–
This is the error I get when I try to install php. What should I do to solve this?
Seems like it might be easy to solve but I am really new to this
From above error looks like you do not have LIBPNG library.
Try installing libpng or libpng12 package via brew first.
If it doesn’t work after that as well, just you share brew commands you have used?
Brew link is pointing to “Page not found”
Is there any detail tutorial on Brew, like what is brew, its pros/cons and how to install and use?
Fixed. There homepage is changed to http://brew.sh/
Brew is package-manager. For pros/cons, you may Google. If you are familiar with MacPorts, you can think of its a better (IMHO) replacement to MacPorts.