- Installing Nginx in Mac OS X Maverick With Homebrew
- Установка php5.5+php-fpm+mysql+nginx на Mac OS X Mavericks
- Xcode
- Homebrew
- PHP-FPM
- Настройка PHP в командной строке
- Настройка автозапуска
- MySQL
- Настройка автозапуска
- Обезопасьте установку
- Проверка соединения
- phpMyAdmin
- Nginx
- Настройка автозапуска
- Протестриуйте веб-сервер
- Дальнейшая настройка
- nginx.conf
- Загрузка PHP FPM
- Создание виртуальных хостов
- Настройка SSL
- Включение виртуальных хостов
- Последние тесты
- Управление сервисами
- Nginx
- PHP-FPM
- MySQL
- beatfactor / install_nginx_macos_source.md
- This comment has been minimized.
- Kwon11 commented Oct 2, 2018
- This comment has been minimized.
- YukunSun commented Oct 28, 2018
- This comment has been minimized.
- rustymagnet3000 commented Apr 24, 2019
- This comment has been minimized.
- NullPointing commented Jul 14, 2019
- This comment has been minimized.
- pleminh commented Jul 17, 2019
- This comment has been minimized.
- fuse98 commented Jul 23, 2019
- This comment has been minimized.
- KarmitoHerry commented Nov 12, 2019
- This comment has been minimized.
- henkosasih commented Jan 26, 2020
- How to Configure and Install Nginx on Mac OS X
- Prerequisites
- Install Nginx
- NGINX on macOS
- Installation Guide
- A little housekeeping
- If you don’t have it, install Homebrew
- Install and start Nginx
- Change the listening port
- Set up sites-available and sites-enabled
- Set macOS to run Nginx when it starts
- Set up your server blocks
Installing Nginx in Mac OS X Maverick With Homebrew
Nov 25, 2015 · 2 min read
Install with brew
Use brew to install the nginx with command:
After install run:
Open Navigator it by going to URL:
The default place of nginx.conf on Mac after installing with brew is:
Changing the default port (8080)
We shall change it to 80. First stop the nginx server if it is running by:
Update thanks @zue666, @pixel67 if apache is running must also stop sudo apachectl stop
Then open nginx.conf with (example vim):
Save configuration and relaunch nginx
Open Navigator it by going to URL:
Update: thanks @pablohenrique * ERROR 403 Forbidden — * dont worry, some other application is already using port 80. probably be skype.
1 Solution 1: Change Skype port in Skype > Preferences > advanced 2 Solution 2: No change server < listen to 80.
That means that nginx will use port 8080 instead of 80. To access it I would use this url http://localhost:8080.
Changing the path of defualt web location
he nginx html folder (brew install only) is by the defult in:
Note: change ** 1.2.3 ** to your nginx version.
The defualt path configuration:
To let say Users/to/www:
After change relaunch nginix server and nginx is now serving pages from your custom folder!
Источник
Установка php5.5+php-fpm+mysql+nginx на Mac OS X Mavericks
Каждый веб-разработчик, выбравший Mac, после первичной настройки системы ищет рабочий инструментарий. И если c IDE и редакторами всё понятно, то что-либо подобное по удобству win-довым OpenServer или Denwer за бесплатно найти трудно. Есть отличное решение MAMP PRO, но оно стоит две тысячи деревянных. Да и работа через Apache некоторых может смутить.
Занимаясь решением этого вопроса, набрёл на интереснейший материал, который рассказывает о том, как при помощи консольного пакет-менеджера Homebrew настроить рабочее пространство буквально за 5-10 минут. Публикую его перевод, потому что кому-нибудь подобная инструкция по настройке веб-окружения на Mac обязательно пригодится.
«Только что получил новый MacBook Pro и решил настроить его с чистого листа, потому что я использую тот же бэкап Time Machine примерно уже четверы года. Хороший шанс избавиться от стэка веб-сервера/LAMP (Linux Apache MySQL PHP) и заменить его Nginx и PHP-FPM как реализацию FastCGI. Ниже вы можете прочесть, как настроить Nginx, PHP-FPM, MySQL и PhpMyAdmin на OS X 10.9 / Mavericks.
Xcode
Прежде всего, установите последнюю версию Xcode через Mac App Store:
Скачать Xcode.app (через Mac App Store)
Как только закончится загрузка, откройте Xcode в папке /Applications и согласитесь с лицензией.
Откройте окно Терминала и установите Xcode через следующую команду:
Подтвердите установку при помощи кнопки Install .
Вернитесь обратно в Xcode, нажмите ⌘ + , для доступа к настройкам и перейдите на вкладку Locations. Установите Command Line Tools на последнюю доступную версию, Xcode 5.0.2 (5A3005) в моём примере:
Homebrew
Теперь необходимо установить Homebrew, который является менеджером пакетов для OS X. Вы возможно уже слышали про apt-get или aptitude на дистрибутивах Linux для установки пакетов и зависимостей для конкретный приложений. brew работает также, только на компьютерах под управлением Mac OS X. Он также удостоверится, что вы получите последние обновления для установленных приложений, так что вам не нужно будет беспокоиться из-за просроченных версиях или брешах в системе безопасности, эксплойтах и так далее.
Прежде всего, нам понадобиться Xquarz:
Теперь нам необходимо загрузить и установить Homebrew при помощи следующей команды:
Поверим на любые конфликты и проблемы:
Обновим репозитории и приложения при помощи Homebrew:
PHP-FPM
Потому как Homebrew не имеет репозитория по-умолчанию для PHP-FPM, нам необходимо его добавить:
Установим PHP-FPM при помощи следующих аргументов:
Homebrew загрузит исходный код PHP-FPM и скомпилирует его аз вас. Дайте ему немного времени, это может занять несколько минут.
Настройка PHP в командной строке
Если вы хотите использовать PHP в командной строке, вам необходимо обновить переменную окружения $PATH в файле
Настройка автозапуска
Удостоверьтесь, что PHP-FPM слушает порт 9000:
Вывод должен выглядеть примерно следующим образом:
MySQL
Следующий шаг для установки MySQL:
Настройка автозапуска
И запустите сервер баз данных:
Обезопасьте установку
Для безопасности нашего MySQL-сервера мы вызовем идущий в компоекте бинарник secure_mysql_installation для смены root-пароля, удаления анонимного пользователя и отключения возможности дистанционного логина под root-ом:
Пожалуйста, укажите текущий пароль, если он уже установлен.
Нажите enter, указав пароль для root-пользователя. По желанию сохраните его в менеджерах паролей LastPass или 1Password.
Да, в них нет необходимости.
Да, нет необходимости в авторизации под root с любого другого IP кроме 127.0.0.1.
Да. Нам не нужны тестовые таблицы.
Перезагрузка таблицы привилегий даст нам возможность удостовериться, что изменения вступили в силу.
Проверка соединения
Введите указанный ранее root-пароль и увидите консоль MySQL:
Закончите сессию при помщи команды \q :
phpMyAdmin
Установите autoconf который необходим для phpMyAdmin:
Установите переменную окружения $PHP_AUTOCONF:
Приступим к установке phpMyAdmin:
Nginx
Установите Nginx при помощи команды:
Настройка автозапуска
Так как мы используем 80 порт, необходимо запускать Nginx под пользователем root:
Протестриуйте веб-сервер
Конфигурация по-умолчанию слушает порт 8080 вместо стандартного для протокола HTTP порта 80. Пока проигнорируем это:
Ответ должен выглядеть следующим образом:
Снова остановим Nginx:
Дальнейшая настройка
nginx.conf
Создайте папки, которые понадобятся нам при последующей конфигурации Nginx:
Удалите текущий файл nginx.conf (который всегда будет доступен по адресу /usr/local/etc/nginx/nginx.conf.default , если вы захотите взглянуть на его код) и загрузите созданные мною настройки при помощи curl с GitHub:
Конфиуграционный файл прост и легковесен насколько это возможно: настройки worker, пути/форматы логов и несколько includes. Ничего лишнего в отличие от nginx.conf.default .
Загрузка PHP FPM
Скачайте мои настройки PHP-FPM с GitHub:
Создание виртуальных хостов
Клонируйте тестовый виртуальный хост (включая рерайты для 404, 403 и phpinfo() ) используя git :
И удалите папку /var/www/.git , чтобы git не отслеживал последующие изменнения.
Настройка SSL
Создайте папку для наших сертификатов SSL и частных ключей:
Сгенерируйте 4096bit RSA ключи и само-подписные сертификаты следюущей командой:
Включение виртуальных хостов
Теперь нам нужно создать симлинки в папке sites-enabled для виртуальных хостов с целью включить их:
Снова стартуем Nginx:
Последние тесты
Вот оно, всё должно работать. Щелкайте на ссылках ниже с целью удостовериться в этом:
Управление сервисами
В силу того, чтоы вам рано или поздно понадобиться перезапустить тот или иной вресив, вам возможно понадобятся дополнительные алиасы:
Вы можете или открыть новое окно/сессию Терминала или же вручную перезагрузить
/.bash_profile при помощи команды:
Теперь вы можете использовать алиасы вместо печатания длинных команд launchctl , как то было выше.
Nginx
Вы можете стартовать, остановить и перезапустить Nginx при помощи команд:
Быстрый доступ к логам:
PHP-FPM
Старт, стоп и перезагрузка PHP-FPM:
MySQL
Старт, стоп и рестарт MySQL-сервера:
Дайте мне знать, если застряли или у вас есть какие-либо дополнения!»
Источник
beatfactor / install_nginx_macos_source.md
Install Nginx on Mac OS from source
no Homebrew required
1. Download Nginx
2. Download the PCRE library
The PCRE library distribution (version 4.4 — 8.41) needs to be downloaded from the PCRE site and extracted. The rest is done by nginx’s ./configure and make. PCRE is required for the http_rewrite_module, and also for regular expressions support in the location directive.
3. Configure Nginx
Compile nginx without SSL support
with SSL support
Download OpenSSL sources and extract:
4. Install Nginx
Add the nginx binary to $PATH :
This comment has been minimized.
Copy link Quote reply
Kwon11 commented Oct 2, 2018
stable version of nginx when I used this article is 1.14.0
Thanks for putting this up man it was a huge help.
This comment has been minimized.
Copy link Quote reply
YukunSun commented Oct 28, 2018
In the section of «with SSL support» ,you maybe spell openssl-1.1.0g.tar.gz wrong ,it should be openssl-1.1.0.tar.gz
This comment has been minimized.
Copy link Quote reply
rustymagnet3000 commented Apr 24, 2019
This is great. Did you want to write about the other option with SSL Support where you point to an existing OpenSSL install?
This comment has been minimized.
Copy link Quote reply
NullPointing commented Jul 14, 2019
how do you actually run nginx once this is all done? Everytime I try, it says «command not found»
This comment has been minimized.
Copy link Quote reply
pleminh commented Jul 17, 2019
how do you actually run nginx once this is all done? Everytime I try, it says «command not found»
This comment has been minimized.
Copy link Quote reply
fuse98 commented Jul 23, 2019
great job. this solved my issue, thanks a lot.
This comment has been minimized.
Copy link Quote reply
KarmitoHerry commented Nov 12, 2019
Can I skip install with SSL support ?
When i try to install without with SSL support. I got this error
/Library/Developer/CommandLineTools/usr/bin/make -f objs/Makefile
make[1]: Nothing to be done for `build’.
/Library/Developer/CommandLineTools/usr/bin/make -f objs/Makefile install
test -d ‘/usr/local/nginx’ || mkdir -p ‘/usr/local/nginx’
test -d ‘/usr/local/nginx/sbin’
|| mkdir -p ‘/usr/local/nginx/sbin’
test ! -f ‘/usr/local/nginx/sbin/nginx’
|| mv ‘/usr/local/nginx/sbin/nginx’
‘/usr/local/nginx/sbin/nginx.old’
cp objs/nginx ‘/usr/local/nginx/sbin/nginx’
cp: /usr/local/nginx/sbin/nginx: Permission denied
make[1]: *** [install] Error 1
make: *** [install] Error 2
anyone have same problem like me ?
This comment has been minimized.
Copy link Quote reply
henkosasih commented Jan 26, 2020
Can I skip install with SSL support ?
When i try to install without with SSL support. I got this error
/Library/Developer/CommandLineTools/usr/bin/make -f objs/Makefile
make[1]: Nothing to be done for `build’.
/Library/Developer/CommandLineTools/usr/bin/make -f objs/Makefile install
test -d ‘/usr/local/nginx’ || mkdir -p ‘/usr/local/nginx’
test -d ‘/usr/local/nginx/sbin’
|| mkdir -p ‘/usr/local/nginx/sbin’
test ! -f ‘/usr/local/nginx/sbin/nginx’
|| mv ‘/usr/local/nginx/sbin/nginx’
‘/usr/local/nginx/sbin/nginx.old’
cp objs/nginx ‘/usr/local/nginx/sbin/nginx’
cp: /usr/local/nginx/sbin/nginx: Permission denied
make[1]: *** [install] Error 1
make: *** [install] Error 2
anyone have same problem like me ?
use chown to give permission to folder ex: sudo chown -R [user] nginx
Источник
How to Configure and Install Nginx on Mac OS X
In this tutorial, I would like to show how to configure and install nginx on Mac OS X. My Mac system is Mavericks 10.9.2.
Prerequisites
You have to install Xcode command line tools.
Install Nginx
Download the latest stable version – nginx 1.4.7.
Unzip the downloaded package by the command “tar xvzf nginx-1.4.7.tar.gz”.
“sudo ./configure”. There is an error displayed:
To fix the error, visit the tutorial page and read “Building nginx from Sources”, in which you can find the link of PCRE library.
Go to PCRE official site, and find the latest version of PCRE library on SourceForge.
Download the package and unzip it by the command “tar xvzf pcre-8.34.tar.bz2”.
Now, you can run the configure file again with the parameters ”sudo ./configure –with-pcre=path”.
Configuration is done.
the default nginx path prefix is “/usr/local/nginx”.
To install nginx, type in “sudo make install”.
Find the executable file “cd /usr/local/nginx/sbin”
Launch nginx “sudo ./nginx”
The nginx is successfully running now!
If you have any questions, just email
Источник
NGINX on macOS
Installation Guide
With little tweaking, it is possible to install the NGINX web server on macOS. This guide first explains how to get NGINX running, and then how to set up the file structure so that it’s identical to the Linux-based version.
A little housekeeping
Before we install Nginx, we need to make sure that no other web server is running on macOS. To do this, we’ll stop Apache:
NOTE If Apache isn’t installed, this will obviously do nothing.
If you don’t have it, install Homebrew
To install Nginx on macOS, we will need Homebrew. If you have not yet installed Homebrew, please follow this guide and do so before continuing.
Install and start Nginx
Once Homebrew is installed, run:
Then, once Nginx has been installed, start it by running:
To check that Nginx is correctly installed, and has started correctly, go to http://localhost:8080 . You should see the default Nginx page.
NOTE If you are installing Nginx on a remote Mac, you’ll need to substitute the localhost in the above URL for the IP address of the remote Mac. For example, if you have installed Nginx on a Mac at 10.0.1.10 , you’d type http://10.0.1.10:8080 .
Change the listening port
By default, Nginx listens on port 8080 on Macs. In most circumstances, you will want it to listen on port 80 instead. Before we do this, we need to temporarily stop Nginx from running:
Next, open the configuration file at /usr/local/etc/nginx/nginx.conf :
The server block in your /usr/local/etc/nginx/nginx.conf file should look as follows:
Save your changes by pressing Ctrl + X , then Y , then Enter . Then restart Nginx:
To test that the change worked, visit http://localhost . You should see the default Nginx page.
NOTE As before, if you have installed Nginx on a remote Mac, you’ll need to substitute the localhost in the above URL for the IP address of the remote Mac. For example, if you have installed Nginx on a Mac at 10.0.1.10 , you’d type http://10.0.1.10 .
Set up sites-available and sites-enabled
Next, we need to set up the traditional sites-enabled and sites-available folder structure:
Having created this structure, we need to tell Nginx where to look for enabled sites. To do this, we’ll open /usr/local/etc/nginx/nginx.conf again:
Then we need place the following line within the http block:
Save your changes by pressing Ctrl + X , then Y , then Enter .
Set macOS to run Nginx when it starts
Finally, we need to tell macOS to run Nginx when it starts. To do this, we’ll create a blank file named homebrew.mxcl.nginx.plist in /Library/LaunchDaemons/ :
And paste the following into it (thanks to jimothyGator for the samples):
Save your changes by pressing Ctrl + X , then Y , then Enter .
Set up your server blocks
Now you are ready to start creating server blocks in exactly the same way as you would in any other Nginx setup.
Источник