- Installing Nginx in Mac OS X Maverick With Homebrew
- Setting up a Nginx web server on macOS
- Homebrew
- Nginx
- Installation
- Configuration
- MySQL
- Установка 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
- How to setup Nginx and PHP7.1 with FPM on Mac OS X without crying
- INSTALLATION
- THE CONFIGURATION
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!
Источник
Setting up a Nginx
web server on macOS
Seeking a satisfactory solution to create a local web server for programming in macOS with PHP and MySQL, I was disappointed that the turnkey solutions were far from equaling the WAMP that may exist on Windows.
But I forgot macOS is a Unix system, and unlike Windows, it’s perfectly possible to create a customized local server with some packages.
We will see how to install Nginx, PHP-FPM and MariaDB (MySQL) on macOS High Sierra thanks to Homebrew package manager.
Homebrew
HomeBrew is a package manager for macOS, that allows to easily install various Unix applications.
To install, simply execute the command shown on the official website:
If you do not already have them, macOS will prompt you to first install Xcode Command Line Tools.
Nginx
Although Apache is natively included with macOS, we propose here to install Nginx, particularly lightweight and easily configurable.
Installation
To install and launch Nginx on startup, we use:
Although we musn’t use sudo with brew install , it is necessary to use it to launch Nginx if we want to use the the default port 80.
Configuration
We want to store our web site in the folder of our choice, and access to the URL http://localhost/ . To do this, edit the configuration file:
To begin, we will have to give to Nginx the permission to access our files and avoid a nasty 403 Forbidden error. To do so, we change the first line, where is your username:
Then, to add a new website, we will add a new section inside the http directive:
We then restart Nginx in order to take this changes into account:
In order to use PHP with Nginx we will use PHP-FPM. Here, we will use PHP 7.2, but you can easily choose any other version:
Then, we re-edit the configuration file:
We modify the line starting with index by:
Finally, add in the section server the following lines to run PHP for all files with the extension .php :
To avoid a File not found. error, we also need to give the right permissions to PHP. In the following file:
Change the following parameter to:
At last, we restart Nginx to activate the changes, and we don’t forget to launch PHP, to avoid a 502 Bad Gateway :
MySQL
We will now install and launch MariaDB:
Finally, complete the installation by choosing a root password for MySQL:
Источник
Установка 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-сервера:
Дайте мне знать, если застряли или у вас есть какие-либо дополнения!»
Источник
How to setup Nginx and PHP7.1 with FPM on Mac OS X without crying
I had problems with my nginx for months. I read a ton of articles online but couldn’t find a solution. Most of what I saw was for php7.0 , and they used php-fpm-sock file which clearly does not exist in php7.1 . Creating and configuring php7.1 to use the sock file was a different kettle of fish on it’s own. I failed at it several times. When I upgraded to High Sierra (which basically wiped my system clean due to multiple failures), I had to start setup all over again. I decided to take my time and actually tackle this nginx setup issue. There was still no tutorial on it that worked for me. I made up my mind to figure it out on my own. Did I? This article will explain how I did it.
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
When installed with homebrew, Nginx’s configuration file would be found in /usr/local/etc/nginx . Open it with any editor you like (I use nano to save time).
We are going to leave everything the way it is and just edit only a few sections. The nginx.config file would be configured properly upon installation to serve static files. All your websites would be in /usr/local/var/www folder so that nginx can see them. Nginx mirrors all the files there to it’s html folder that can be found in /usr/local/Cellar/nginx/[version_number]/html as of this writing. If you want to set a different part for your files, edit this block of the config file and set a different root .
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.
I left the fastcgi_param line commented out just incase you need to set something there later. All params are already included below it and the fastcgi.conf file should have all the settings required to use php-fpm . Save your file and restart nginx.
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.
Источник