sylvain durand

Setting up a Nginx 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 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 Homebrew officiel website.

Nginx

Although Apache is natively included with macOS, we propose here to install Nginx, particularly lightweight and easily configurable. To install and launch Nginx on startup, we use:

brew install nginx
brew services start nginx

Now, localhost:8080 should show Welcome to nginx!.

The configuration file is located at /opt/homebrew/etc/nginx/nginx.conf. Here is a minimal working example showing a website in your home folder:

worker_processes  1;

events {
  worker_connections 1024;
}

http {
  include mime.types;
  default_type application/octet-stream;
  sendfile on;
  keepalive_timeout 65;
  gzip on;

  server {
    listen       8080;
    server_name  localhost;

    location / {
      root   /Users/<user>/my_website;
      index  index.html;
    }
  }
}

We then restart Nginx in order to take this changes into account:

brew services restart nginx

PHP

In order to use PHP with Nginx we will use PHP-FPM:

brew install php

Then, we re-edit the configuration file to use index.php instead of index.html:

index index.php;

Finally, add in the section server the following lines to run PHP for all files with the extension .php:

location ~ \.php {
  fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
  include fastcgi_params;
  fastcgi_pass 127.0.0.1:9000;
  fastcgi_split_path_info ^(.+\.php)(/.+)$;
  fastcgi_buffers 16 16k;
  fastcgi_buffer_size 32k;
}

Then, we take these changes into account and start PHP:

brew services restart nginx
brew services start php

MySQL

We will now install and launch MariaDB:

brew install mariadb
brew services start mariadb

Here is the perfect MAMP installation!