Switching to NGINX


Last Friday I switched the web server running on my Mac Mini (MacOS) from Apache to Nginx.

The main motivations for moving to Nginx, in my case, are:

  1. Nginx is faster at serving static content
  2. Configuration is simpler
  3. Nginx can be easily updated using Homebrew

Here is a recap of what I did.

Installing Nginx

Do the following:

brew install nginx --with-gunzip --with-passenger

Check whether the installation succeeded:

$ nginx
$ curl http://localhost:8080
<if content returned here, installation succeeded>

Stop Nginx with:

$ nginx -s stop

Launching Nginx at boot

Now we need to ensure Nginx starts at boot. The standard way of doing it on MacOS is by installing Nginx’s launchctl scripts: brew info nginx will give you the instructions.

However, I like cron much more and in my case the solution is the following:

crontab -e

and then add the following line:

@reboot /usr/local/bin/nginx

If you are serving Rails applications and are using a Ruby version manager such as chruby, you also need to specify which version of Ruby has to be used by Nginx. In this case, add the following line to your cron jobs:

@reboot chruby-exec ruby-2.2.3 -- /usr/local/bin/nginx

Serving Content

By default Nginx listens to port 8080. If you are going to use Nginx to serve content on the Internet, you have two main choices:

  1. Port forwarding Configure your router so that is forwards requests it receives on port 80 to port 8080 on the machine where nginx is installed.
  2. Change the default port Nginx uses Edit the configuration file of Nginx (found in /usr/local/etc/nginx/nginx.conf) and change the default port (look for 8080 and replace it with 80).

Finally, make sure you configure the MacOS Firewall so that nginx can accept incoming connections! This is achieved by editing the Firewall panel in System Preferences.

Complete the Switchover

We can now switch off Apache and start Nginx. This is as simple as:

nginx -t
sudo apachectl stop; nginx

sudo is necessary if you are running the web server on a port below

As a final remark, make sure you unload the Apache launchctl script, or Apache will launch next time your computer reboots! This is done with:

sudo launchctl unload -w /System/Library/LaunchDaemons/org.apache.httpd.plist