Altoplace

Configure Apache and PHP-FPM on macOS

Apple Computer.
Image by Pexels from Pixabay .

Contents

Introduction

Note (1/8/22): I made some minor updates and bug fixes to my control scripts. This coming year, I will move them to GitHub.

Over the last few months, I have experimented with different hosting arrangements, WordPress, and Hugo CMS configurations. Now it’s time to start creating content to see if I can create a viable site. To that end, I want to start by writing about my efforts to create a local website development environment on my Mac.

As a foundation, I have chosen Homebrew to install most of the software that I am using. Please go to their site for installation instructions. It’s not the only game in town. Apple does provide a web development environment, but their software may be (slightly) out-of-date or hard to configure. MacPorts is another good option. After trying out both, I had a hard time deciding, but finally chose Homebrew for it’s popularity and ease of use.

This post is just about Apache and PHP; I wrote about MySQL in a separate post. I originally wrote this post for macOS Catalina, but I just updated it for macOS Big Sur. In this post, I also describe some tools that I wrote to manage Apache and PHP processes.

Note: I just recently moved my site from WordPress to Hugo. Apache plus php-fpm is still a great environment for testing a deployed Hugo site. PHP is mostly not needed (although, my contact form does use PHP). MySQL is definitely not needed for a Hugo site.

Using the Apache Event Module

There are multiple sites that describe how to install Apache and PHP on a Mac using Homebrew. But most of them describe using Apache with the pre-fork Multi-Processing Module (MPM). That’s understandable since Homebrew installs Apache with the pre-fork module active. But in the Linux world, the current, default module is the event module. This allows you to run PHP as a separate process, which is called on as needed. With the pre-fork module, PHP is built in (with mod_php) and is executed all the time even if PHP is not required to fulfill the request.

Running Apache with the pre-fork module is probably just fine while working with a local development environment. But I wanted to learn how to use it with the event module, running PHP as a separate process. By the way, you should check out “macOS 12.0 Monterey Apache Setup: Multiple PHP Versions .” This is one of the best posts that I have seen about setting up a local website development environment. It has inspired much of what I have done to setup my local development environment. It also uses Homebrew to install most of the software.

Install Apache with the brew command

Let’s get started; the first step is to install Apache, using Homebrew. Please install Homebrew and verify your installation if you haven’t done so.

$ brew doctor
Your system is ready to brew.

$ brew install httpd

$ which -a httpd
/usr/local/bin/httpd
/usr/sbin/httpd

$ httpd -v
Server version: Apache/2.4.47 (Unix)
Server built:   May 12 2021 11:12:57

$ httpd -V | grep MPM
Server MPM:     prefork

First, we verified that Homebrew is ready to go. Next, we installed Apache (and a number of dependencies). Finally, we ran a couple of commands to check the installation. Note, use the which command to verify that the Homebrew version of Apache is first in your PATH (you will have to restart your terminal session). The last command shows that Apache was installed with the prefork module enabled.

Great. Now, let’s start it up and test it with Safari:

$ brew services start httpd
==> Tapping homebrew/services
Cloning into '/usr/local/Homebrew/Library/Taps/homebrew/homebrew-services'...
remote: Enumerating objects: 1188, done.
remote: Counting objects: 100% (67/67), done.
remote: Compressing objects: 100% (56/56), done.
remote: Total 1188 (delta 22), reused 18 (delta 10), pack-reused 1121
Receiving objects: 100% (1188/1188), 352.17 KiB | 3.67 MiB/s, done.
Resolving deltas: 100% (498/498), done.
Tapped 1 command (43 files, 449KB).
==> Successfully started `httpd` (label: homebrew.mxcl.httpd)

(The first time you run the brew services command, it will add the Homebrew-services tap.) Click on: http://localhost:8080 to test that Apache is running. You should see It Works! in your Safari browser. Note, that you had to specify the non-standard 8080 port number as part of the URL. That’s because Homebrew does not like using sudo, which is required if you want to start up Apache with the standard port 80 configuration. That’s called a privileged port and requires root privileges.

If you don’t see “It Works!”, then you need to do some troubleshooting. Make sure that httpd is actually running. I have seen cases where the brew services command said that it started, but it either didn’t start or died right away (later on I will describe my a2ctl tool for starting and stopping httpd; it does additional error checking). Let’s verify that the httpd processes are running:

$ ps -x | egrep httpd | sed '/grep/d' 
 6791 ??         0:00.05 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
 6802 ??         0:00.00 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
 6803 ??         0:00.00 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
 6804 ??         0:00.00 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
 6805 ??         0:00.00 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
 6806 ??         0:00.00 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
 6967 ??         0:00.00 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
 6975 ??         0:00.00 /usr/local/opt/httpd/bin/httpd -D FOREGROUND

If you do not see a list of httpd processes, or you are still having issues, please check the Apache error log file.

$ tail -f /usr/local/var/log/httpd/error_log

It will usually show what went wrong.

As you may have guessed, this is how we stop Apache:

$ brew services stop httpd 
Stopping `httpd`... (might take a while)
==> Successfully stopped `httpd` (label: homebrew.mxcl.httpd)

Switching Apache to the event module and port 80

Using port 80

Next, I want to change my Apache configuration to use the event module and port 80. To start and stop Apache when using privilege ports, sudo has to be used. Homebrew is designed to not use sudo. You will see examples of it being used, but in my experience, the brew services … command does not play nicely with sudo. Therefore, I wrote my own shell script to start and stop Apache.

Make sure that you have stopped Apache with the above brew services command. I wrote a shell script called a2ctl to start, stop, or restart Apache:

#!/bin/zsh

# Usage: a2ctl start|stop|restart|status

error_exit()
{
  echo -e "$1" 1>&2
  exit 1
}

# Usage
if [[ ! $# -eq 1 || ! ($1 == "start" || $1 == "stop" || $1 == "restart" || $1 == "status") ]]
then
  error_exit "Usage: a2ctl start|stop|restart|status"
else
  action="$1"
fi

pwait()
{ 
  process=$1
  action=$2
  count=0
  
  if [[ $action == "stop" ]]
  then
    until ! pgrep -q $process || [[ $count -gt 5 ]]
    do
      echo "waiting for $process to stop $count ..."
      sleep 1
      ((count++))
    done 
    if ! pgrep -q $process; then
      echo "$process stopped OK ..."
    else
      error_exit "$process failed to stop"
    fi
  else
    # action is start 
    sleep 1 # give process time to die for configuration file errors ...
    until pgrep -q $process || [[ $count -gt 5 ]]
    do
      echo "waiting for $process to start $count ..."
      sleep 1
      ((count++))
    done
    if pgrep -q $process; then
      echo "$process started OK ..."
    else
      error_exit "$process failed to start"
    fi
  fi
}

a2start()
{
  if pgrep -q httpd; then
    echo "Apache is already started ..."
    exit 0
  fi
  
  if [ ! -f "/usr/local/opt/httpd/homebrew.mxcl.httpd.plist" ]; then
    error_exit "Cannot start Apache -- homebrew.mxcl.httpd.plist is missing ..."
  fi
  
  sudo cp /usr/local/opt/httpd/homebrew.mxcl.httpd.plist /Library/LaunchDaemons/
  if [ "$?" != "0" ]; then
    error_exit "homebrew.mxcl.httpd.plist copy failed ..."
  fi
  
  sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.httpd.plist > /dev/null 2>&1
  pwait httpd start
}

a2stop()
{
#  if ! pgrep -q httpd; then
#    echo "Apache is already stopped ..."
#    exit 0
#  fi
 
  sudo launchctl unload /Library/LaunchDaemons/homebrew.mxcl.httpd.plist > /dev/null 2>&1
  pwait httpd stop

  # Don't start automatically
  sudo rm -f /Library/LaunchDaemons/homebrew.mxcl.httpd.plist
}

a2restart()
{
  # First, stop Apache ...
#  if ! pgrep -q httpd; then
#    echo "Apache is already stopped, so just start it up ..."
#    a2start
#    exit 0
#  fi

#  sudo launchctl unload /Library/LaunchDaemons/homebrew.mxcl.httpd.plist > /dev/null 2>&1
#  pwait httpd stop

  # Then, start Apache ...
#  sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.httpd.plist > /dev/null 2>&1
#  pwait httpd start
  a2stop
  a2start
}

a2status()
{
  # Get status about running httpd processes
  ps -axo user,pid,start,etime,time,nice,vsz,rss,command |\
    egrep '^USER|httpd' | sed '/grep/d'
}

case $action in
  "start")
    a2start
    ;;
  "stop")
    a2stop
    ;;
  "restart")
    a2restart
    ;;
  "status")
    a2status
    ;;
  *)
    # Should never happen ...
    error_exit "Invalid action ..."
    ;;
esac

exit 0

As noted by the Usage comment, it is very easy to use. Once started, Apache will start automatically when the macOS system is restarted. If stopped, Apache will not start when the system restarts. If stopped or running, restart will (re)start Apache. Now that we have our new Apache start/stop script, lets update our Apache configuration to use port 80:

$ cd /usr/local/etc/httpd

$ mkdir -p ~/orig/usr/local/etc/httpd

$ cp httpd.conf ~/orig/usr/local/etc/httpd

# Use your favorite text editor ...
$ vi httpd.conf

$ diff ~/orig/usr/local/etc/httpd/httpd.conf .
52c52
< Listen 8080
---
> Listen 80

223c223
< #ServerName www.example.com:8080
---
> ServerName localhost

$ a2ctl start
Password:
httpd started OK ...

Now, go to http://localhost (dropping the 8080) and you should see It Works! again.

It seems that on macOS Big Sur, the brew services command will still run httpd ok after changing to port 80. I am not sure if that’s always the case. I am sticking with using sudo in a2ctl to stay consistent with my Linux experience. Feel free to experiment for yourself. BTW, you can use a2ctl to check the status of your running httpd processes:

$ a2ctl status
USER               PID STARTED     ELAPSED      TIME NI      VSZ    RSS COMMAND
root              7939 12:20PM       00:06   0:00.02  0  4431348   4404 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
_www              7941 12:20PM       00:06   0:00.00  0  4310480   1076 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
_www              7942 12:20PM       00:06   0:00.00  0  4310480   1088 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
_www              7943 12:20PM       00:06   0:00.00  0  4302288   1076 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
_www              7944 12:20PM       00:06   0:00.00  0  4302288   1092 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
_www              7945 12:20PM       00:06   0:00.00  0  4326864   1100 /usr/local/opt/httpd/bin/httpd -D FOREGROUND

Switching to the event module

Make the following changes to switch Apache to the event module:

$ cd /usr/local/etc/httpd

$ vi httpd.conf

$ diff ~/orig/usr/local/etc/httpd/httpd.conf .
 o o o
66,67c66,67
< #LoadModule mpm_event_module lib/httpd/modules/mod_mpm_event.so
< LoadModule mpm_prefork_module lib/httpd/modules/mod_mpm_prefork.so
---
> LoadModule mpm_event_module lib/httpd/modules/mod_mpm_event.so
> #LoadModule mpm_prefork_module lib/httpd/modules/mod_mpm_prefork.so

488c488
< #Include /usr/local/etc/httpd/extra/httpd-mpm.conf
---
> Include /usr/local/etc/httpd/extra/httpd-mpm.conf

$ a2ctl restart
Password:
httpd stopped OK ...
httpd started OK ...

$ httpd -V | grep MPM
Server MPM:     event

We commented out the prefork module and uncommitted the event module. Uncommenting the Include httpd-mpm.conf file is optional, but it allows updating the number of httpd event servers, etc. This is the default event MPM configuration defined in this file:

$ cd /usr/local/etc/httpd/extra

$ cat httpd-mpm.conf
 o o o
# event MPM
# StartServers: initial number of server processes to start
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxRequestWorkers: maximum number of worker threads
# MaxConnectionsPerChild: maximum number of connections a server process serves
#                         before terminating
<IfModule mpm_event_module>
    StartServers             3
    MinSpareThreads         75
    MaxSpareThreads        250
    ThreadsPerChild         25
    MaxRequestWorkers      400
    MaxConnectionsPerChild   0
</IfModule>
 o o o

Change Document Root to the Local User

Because we are setting up a Development environment (don’t do this on a production system), we will move our Document Root to our local user Sites directory. Make the following changes to httpd.conf (changing user to your local user):

# Set local user ...

193,194c193,194
< User _www
< Group _www
---
> User user
> Group staff

# Update Document Root to point to the local user

248,249c248,249
< DocumentRoot "/usr/local/var/www"
< <Directory "/usr/local/var/www">
---
> DocumentRoot /Users/user/Sites
> <Directory /Users/user/Sites>
269c269
<     AllowOverride None
---
>     AllowOverride All

# Restart apache ...

$ a2ctl restart
Password:
httpd stopped OK ...
httpd started OK ...

By the way, if something doesn’t go right, be sure to check the Apache error log at /usr/local/var/log/httpd/error_log. For the “started OK” case you should see a line that says “resuming normal operations.” Also, take a look at the a2ctl status output:

$ a2ctl status 
USER               PID STARTED     ELAPSED      TIME NI      VSZ    RSS COMMAND
root            8859 12:46PM       00:08   0:00.02  0  4440840   4720 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
user            8861 12:46PM       00:08   0:00.00  0  4332580   1468 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
user            8862 12:46PM       00:08   0:00.00  0  4341796   1476 /usr/local/opt/httpd/bin/httpd -D FOREGROUND
user            8863 12:46PM       00:08   0:00.00  0  4333604   1496 /usr/local/opt/httpd/bin/httpd -D FOREGROUND

Apache starts up with root ownership and then it spawns the user processes.

Let’s test our new local user root directory. Create a index.html in your ~/Sites directory and test it in your Safari browser:

$ mkdir -p ~/Sites

$ cd ~/Sites

$ vi index.html

$ cat index.html
<h1>Our Local User Web Root</h1>

Go to http://localhost . You should see Our Local User Web Root in your browser (you may need to refresh your browser). If all is good, we can move on to installing and configuring PHP-FPM.

Install and Configure PHP-FPM

I have configured Apache to work with the event module and our local Sites document root. Now let’s make the Apache configuration changes to talk to PHP-FPM. We will enable the mod_proxy_fcgi and mod_proxy modules along with httpd.conf changes to enable FastCGI support. You can read more about how this works at the Apache Module mod_proxy_fcgi website. Finally, I will install and configure PHP-FPM.

Configure Apache to work with PHP-FPM

Edit httpd.conf with your favorite text editor. Make the following changes:

131c131
< #LoadModule proxy_module lib/httpd/modules/mod_proxy.so
---
> LoadModule proxy_module lib/httpd/modules/mod_proxy.so
135c135
< #LoadModule proxy_fcgi_module lib/httpd/modules/mod_proxy_fcgi.so
---
> LoadModule proxy_fcgi_module lib/httpd/modules/mod_proxy_fcgi.so

282c282
<     DirectoryIndex index.html
---
>     DirectoryIndex index.php index.html

# and add this block right after the dir_module block ...

# Run php-fpm via proxy_fcgi
<IfModule proxy_fcgi_module>
    <FilesMatch "\.php$">
        SetHandler "proxy:unix:/usr/local/var/run/php-fpm.sock|fcgi://localhost"
    </FilesMatch>
</IfModule>

Restart Apache with the above changes:

$ a2ctl restart
Password:
httpd stopped OK ...
httpd started OK ...

Check the Apache error log if it doesn’t start up OK. At this point Apache is ready to run PHP. We don’t have to touch it again. We can install PHP, change PHP versions, etc., and Apache will keep talking to the currently running PHP version. So let’s move on to our PHP install.

Setting up PHP-FPM to work with Apache

As of this writing, the newest version of PHP is version 8.0. However, my Pair Networks shared host is using version 7.4. The following instructions will describe how to install and configure PHP version 7.4 as the default version of PHP. I will also install version 8.0. We could use the brew services command to start and stop the PHP-FPM service. But I opted to write a shell script to start and stop PHP-FPM. I can also easily switch PHP versions with my shell script. I will also update the PHP-FPM configuration file to use a Unix socket to talk to Apache (which is ready to go on the Apache side). The PHP brew installation defaults to using a TCP/IP socket, but the Unix socket approach has less overhead. You can read about what’s the difference between a Unix socket and a TCP/IP socket .

Let’s frist install PHP versions 7.4 and 8.0:

$ brew install php@7.4

$ brew install php

# Set the active version of PHP to version 7.4

$ brew unlink php && brew link --overwrite --force php@7.4

# Restart your terminal session ...

$ php -v
PHP 7.4.19 (cli) (built: May 13 2021 06:28:47) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.19, Copyright (c), by Zend Technologies

$ brew services start php@7.4
==> Successfully started `php@7.4` (label: homebrew.mxcl.php@7.3)

The first brew command installed PHP version 7.4 and a bunch of dependencies. The second install command installed the latest production version of PHP, which is currently version 8.0. Finally, the third brew command switched the default version of PHP to version 7.4. Note: Be sure to restart your terminal session after completing the brew link command. Then you can verify your PHP version, and I also showed how to start the PHP-FPM services with the brew services command. For now, stop PHP-FPM with the _brew services stop php@7._4 command. We need to update the PHP-FPM configuration file, so that it will be able to talk to Apache.

Starting and Stopping PHP-FPM

You can continue using the brew services command to start and stop PHP-FPM. I prefer having a little more control for starting and stopping, including verifying that PHP-FPM actually did start. I have seen cases where the brew services command will report a successful start, but PHP-FPM actually did not start (or died immediately). I also wanted to implement a convenient way to switch PHP versions. Therefore, I wrote a shell script called phpctl to start, stop, and restart PHP-FPM. I also included an status action to get information about the running PHP-FPM processes. But before we get into the details about phpctl, let’s update the PHP-FPM configuration for Apache (and some additional tweaks).

First, change directory to /usr/local/etc/php/PHP_VERSION/php-fpm.d. The default PHP-FPM configuration is in www.conf. You will want to save a copy of that file in a safe place because it has a lot of useful comments in it, but we are going to filter out all the commented lines and make our Unix proxy changes and point to our local user (which you need to update):

$ pwd
/usr/local/etc/php/7.4/php-fpm.d

$ mkdir -p ~/orig/usr/local/etc/php/7.4/php-fpm.d

$ cp www.conf ~/orig/usr/local/etc/php/7.4/php-fpm.d

# Strip out all the comments ...

$ cat www.conf | egrep -v "^;" | egrep -v "^$" > tmpfile

$ mv tmpfile www.conf

$ cat www.conf
[www]
user = _www
group = _www
listen = 127.0.0.1:9000
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

# Update www.conf to use a Unix socket and our local user ...

$ cat www.conf
[www]
user = user
group = staff
listen = /usr/local/var/run/php-fpm.sock
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

Now we are ready to test that PHP-FPM is working with Apache. You will need to first stop (if not stopped already) and then start PHP-FPM with the brew services command. Next, we will create a simple info.php PHP script to test that everything is working:

$ brew services stop php@7.4 
Stopping `php@7.4`... (might take a while)
==> Successfully stopped `php@7.4` (label: homebrew.mxcl.php@7.4)

$ brew services start php@7.4
==> Successfully started `php@7.4` (label: homebrew.mxcl.php@7.4)

$ cd ~/Sites

$ vi info.php

$ cat info.php
<?php
  phpinfo();
?>

Go to http://localhost/info.php . You should see the PHP info screen with lots and lots of information about your running PHP installation. Note that the Server API shows FPM/FastCGI. If all is good, then we are about done with the exception of optionally using my p7ctl PHP control script. Also, don’t forget to make the same www.conf changes for PHP-FPM 8.0.

$ brew services stop php@7.4
Stopping `php@7.4`... (might take a while)
==> Successfully stopped `php@7.4` (label: homebrew.mxcl.php@7.4)

$ cd ../../8.0/php-fpm.d

$ php -v
PHP 7.4.19 (cli) (built: May 13 2021 06:28:47) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.19, Copyright (c), by Zend Technologies

$ brew unlink php && brew link --force --overwrite php@8.0
Unlinking /usr/local/Cellar/php@7.4/7.4.19_1... 25 symlinks removed.
Linking /usr/local/Cellar/php/8.0.6_1... 24 symlinks created.

$ php -v
PHP 8.0.6 (cli) (built: May 13 2021 05:36:01) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.0.6, Copyright (c) Zend Technologies
    with Zend OPcache v8.0.6, Copyright (c), by Zend Technologies

# Update www.conf like we did for version 7.4:

$ cat www.conf
[www]
user = user
group = staff
listen = /usr/local/var/run/php-fpm.sock
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

$ brew services start php@8.0
==> Successfully started `php` (label: homebrew.mxcl.php)

# Again, run the info.php script in Safari:
# http://localhost/info.php

$ brew services stop php@8.0 
Stopping `php`... (might take a while)
==> Successfully stopped `php` (label: homebrew.mxcl.php)

Go to http://localhost/info.php to test. I actually showed how you can manually switch PHP-FPM services. You can actually start different PHP-FPM versions without doing the unlink and link commands. But I prefer keeping the Command Line Version of PHP (php -v) in sync with the PHP-FPM version. Also, I don’t know if there could be other side affects from not unlinking and linking.

Using phpctl instead of the brew services command

I wrote a shell script, phpctl, to have a little finer control for stopping and starting PHP-FPM. I can easily use it to switch the running version of PHP-FPM (currently, version 7.4 or 8.0). You simply stop the running version and start the new version. Here is my phpctl shell script:

#!/bin/zsh

# Usage: phpctl start [7.4|8.0|8.1] -- starts 7.4, 8.0, or 8.1
#          (defaults to currently linked version)
#        phpctl restart -- restarts the currently linked version
#        phpctl stop -- stops the currently linked and running version
#        phpctl status -- get info about running php-fpm processes
#
#        The start action will unlink the current version and link
#        the requested version if different from the linked version.
#        The restart and stop actions only work with the
#        currently linked version.

error_exit()
{
  echo -e "$1" 1>&2
  exit 1
}

# Get the currently linked PHP version ...
linked="php@$(/usr/local/bin/php -v | grep ^PHP | cut -d' ' -f2 | cut -d'.' -f1,2)"

# Get command parameters ...
if [[ ! $# -ge 1 || ! ($1 == "start" || $1 == "stop" || $1 == "restart" || $1 == "status" ) ]]; then
  error_exit "Usage:\tphpctl start [7.4|8.0|8.1]\n\tphpctl restart\n\tphpctl stop\n\tphpctl status"
else
  action="$1"
  if [[ -z $2 ]]; then
    # Default to the linked version
    version=${linked}
  elif [[ ! ($2 == "7.4" || $2 == "8.0" || $2 == "8.1" ) ]]; then
    error_exit "Version $2 is not supported."
  else
    version="php@$2"
  fi
fi

# plist file name format can change (e.g., php vs php@7.4)
plfile=$(find /usr/local/opt/${linked}/homebrew.mxcl.php*.plist)
if [[ $? -ne 0 ]]; then
  error_exit "Did not find linked ${linked} plist file ..."
fi

pwait()
{
  process=$1
  action=$2
  count=0

  if [[ $action == "stop" ]]
  then
    until ! pgrep -q $process || [[ $count -gt 5 ]]
    do
      echo "waiting for $process to stop $count ..."
      sleep 1
      ((count++))
    done
    if ! pgrep -q $process; then
      echo "$process stopped OK ..."
    else
      error_exit "$process failed to stop"
    fi
  else
    # action is start
    sleep 1 # give process time to die for configuration file errors ...
    until pgrep -q $process || [[ $count -gt 5 ]]
    do
      echo "waiting for $process to start $count ..."
      sleep 1
      ((count++))
    done
    if pgrep -q $process; then
      echo "$process started OK ..."
    else
      error_exit "$process failed to start"
    fi
  fi
}

php_start()
{
  if pgrep -q php-fpm; then
    echo "${linked} is already started."
    exit 0
  fi
 
  if [[ ${linked} != ${version} ]]; then
    brew unlink ${linked} > /dev/null 2>&1 &&
      brew link --force --overwrite ${version} > /dev/null 2>&1
    linked=${version}
    plfile=$(find /usr/local/opt/${linked}/homebrew.mxcl.php*.plist)
    if [[ $? -ne 0 ]]; then
      error_exit "Did not find linked ${linked} plist file ..."
    fi
  fi

  cp ${plfile} ~/Library/LaunchAgents/
  if [[ $? -ne 0 ]]; then
    error_exit "${plfile} copy failed ..."
  fi
  
  launchctl load ~/Library/LaunchAgents/$(basename ${plfile}) > /dev/null 2>&1
  pwait php-fpm start
}

php_stop()
{
  if ! pgrep -q php-fpm; then
    echo "${linked} is already stopped ..."
    exit 0
  fi
 
  launchctl unload ~/Library/LaunchAgents/$(basename ${plfile}) > /dev/null 2>&1
  pwait php-fpm stop

  # Don't start automatically
  rm -f ~/Library/LaunchAgents/$(basename ${plfile})
}

php_restart()
{

  # First, stop PHP ...
  if ! pgrep -q php-fpm; then
    echo "${linked} is already stopped, so just start it up ..."
    # Always restart the linked version
    if [[ ${version} != ${linked} ]]; then
      version=${linked}
    fi
    php_start
    exit 0
  fi

  launchctl unload ~/Library/LaunchAgents/$(basename ${plfile}) > /dev/null 2>&1
  pwait php-fom stop

  # Then, start PHP ...
  launchctl load ~/Library/LaunchAgents/$(basename ${plfile}) > /dev/null 2>&1
  pwait php-fpm start
}

php_status()
{
  ps -axo user,pid,start,etime,time,nice,vsz,rss,command |\
    egrep '^USER|php-fpm' | sed '/grep/d'
}

case $action in
  "start")
    php_start
    ;;
  "stop")
    php_stop
    ;;
  "restart")
    php_restart
    ;;
  "status")
    php_status
    ;;
  *)
    # Should never happen ...
    error_exit "Invalid action ..."
    ;;
esac

exit 0

Here are some examples of how to use it (first, be sure to run brew services stop php@8.0 if you previously started PHP-FPM with the brew services start command):

# The currently linked version of PHP
$ php -v
PHP 8.0.10 (cli) (built: Aug 26 2021 15:36:17) ( NTS )
Copyright (c) The PHP Group
Zend Engine v4.0.10, Copyright (c) Zend Technologies
    with Zend OPcache v8.0.10, Copyright (c), by Zend Technologies

# Start the currently linked version of PHP-FPM
$ phpctl start
php-fpm started OK ...

# Trying to start again ...
$ phpctl start
php@8.0 is already started.

# Get info about our running PHP-FPM processes
$ phpctl status
USER               PID STARTED  ELAPSED      TIME NI      VSZ    RSS COMMAND
george           16461 12:21PM    00:24   0:00.04  0  4749016  13796 /usr/local/opt/php/sbin/php-fpm --nodaemonize
george           16463 12:21PM    00:24   0:00.00  0  4748760    752 /usr/local/opt/php/sbin/php-fpm --nodaemonize
george           16464 12:21PM    00:24   0:00.00  0  4757976    756 /usr/local/opt/php/sbin/php-fpm --nodaemonize

# Stop the running version
$ phpctl stop
php-fpm stopped OK ...

# Start a different version (and unlink and link)
phpctl start 7.4
php-fpm started OK ...

# Confirm new linked version
$ php -v
PHP 7.4.23 (cli) (built: Aug 27 2021 09:20:14) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.23, Copyright (c), by Zend Technologies

# Get info about our new running PHP-FPM processes
$ phpctl status
USER               PID STARTED  ELAPSED      TIME NI      VSZ    RSS COMMAND
george           16824 12:24PM    00:28   0:00.04  0  5018696  13884 /usr/local/opt/php@7.4/sbin/php-fpm --nodaemonize
george           16826 12:24PM    00:28   0:00.00  0  5017416    744 /usr/local/opt/php@7.4/sbin/php-fpm --nodaemonize
george           16827 12:24PM    00:28   0:00.00  0  5026632    732 /usr/local/opt/php@7.4/sbin/php-fpm --nodaemonize

Setting up Virtual Hosts

At this point, Apache and PHP-FPM is working with our Mac localhost. The last item that we want to configure is our virtual hosts environment. We want to be able to create testing host domains that are local to our Mac. For example, I have created a local test domain called altoplace.tst.

For each virtual host, we need a DNS entry, so that we’re able to enter that name into our Safari (or your favorite) browser on your Mac. We could add an entry for each virtual host to our /etc/hosts file, but instead of doing that, we will install a lightweight DNS server on our Mac that will resolve any domain name ending in txt (or test, or whatever local TLD you choose). Of course, don’t pick a real TLD. Also, I understand that the current version of Google Chrome forces all .dev domains to use SSL, so .dev might not be a good choice. We are going to install and use dnsmasq, using Homebrew. Also, I will show you my shell script, dnsctl, that I use to start and stop dnsmasq. Dnsmasq requires root privileges, and as I noted before, the brew services command does not play well with the sudo command.

Using a lightweight DHCP and caching DNS server, dnsmasq

Run the following commands to install and configure dnsmasq:

$ brew install dnsmasq

$ sudo mkdir -p /etc/resolver

$ cd /usr/local/etc

$ mkdir -p ~/orig/usr/local/etc

$ cp dnsmasq.conf ~/orig/usr/local/etc

$ vi dnsmasq.conf

$ diff ~/orig/usr/local/etc/dnsmasq.conf .
79a80
> address=/.tst/127.0.0.1

$ sudo bash -c 'echo "nameserver 127.0.0.1" > /etc/resolver/tst'

The last three lines creates our .tst domain. Actually, I made this a bit more complicated than needed. You could have just created a one line dnsmasq.conf file that contains address=/.tst/127.0.0.1. None of the other configuration options in this file are turned on for our simple application, but I wanted to keep the file as is in case I choose to make other configuration changes in the future.

At this point, we are ready to start the dnsmasq service. However, it needs to be started with root privileges, so I am going to again create my own shell script to start and stop dnsmasq. I called it dnsctl:

#!/bin/zsh

# Usage: dnsctl start|stop|restart|status

error_exit()
{
  echo -e "$1" 1>&2
  exit 1
}

# Usage
if [[ ! $# -eq 1 || ! ($1 == "start" || $1 == "stop" || $1 == "restart" || $1 == "status") ]]
then
  error_exit "Usage: dnsctl start|stop|restart|status"
else
  action="$1"
fi

pwait()
{
  process=$1
  action=$2
  count=0

  if [[ $action == "stop" ]]
  then
    until ! pgrep -q $process || [[ $count -gt 5 ]]
    do
      echo "waiting for $process to stop $count ..."
      sleep 1
      ((count++))
    done
    if ! pgrep -q $process; then
      echo "$process stopped OK ..."
    else
      error_exit "$process failed to stop"
    fi
  else
    # action is start
    sleep 1 # give process time to die for configuration file errors ...
    until pgrep -q $process || [[ $count -gt 5 ]]
    do
      echo "waiting for $process to start $count ..."
      sleep 1
      ((count++))
    done
    if pgrep -q $process; then
      echo "$process started OK ..."
    else
      error_exit "$process failed to start"
    fi
  fi
}

dnsstart()
{
  if pgrep -q dnsmasq; then
    echo "dnsmasq is already started ..."
    exit 0
  fi
  
  if [ ! -f "/usr/local/opt/dnsmasq/homebrew.mxcl.dnsmasq.plist" ]; then
    error_exit "Cannot start dnsmasq -- homebrew.mxcl.dnsmasq.plist is missing ..."
  fi
  
  sudo cp /usr/local/opt/dnsmasq/homebrew.mxcl.dnsmasq.plist /Library/LaunchDaemons/
  if [ "$?" != "0" ]; then
    error_exit "homebrew.mxcl.dnsmasq.plist copy failed ..."
  fi
  
  sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist > /dev/null 2>&1
  pwait dnsmasq start
}

dnsstop()
{
  if ! pgrep -q dnsmasq; then
    echo "dnsmasq is already stopped ..."
    exit 0
  fi
 
  sudo launchctl unload /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist > /dev/null 2>&1
  pwait dnsmasq stop

  # Don't start automatically
  sudo rm -f /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist
}

dnsrestart()
{
  # First, stop dnsmasq ...
  if ! pgrep -q dnsmasq; then
    echo "dnsmasq is already stopped, so just start it up ..."
    dnsstart
    exit 0
  fi

  sudo launchctl unload /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist > /dev/null 2>&1
  pwait dnsmasq stop

  # Then, start dnsmasq ...
  sudo launchctl load /Library/LaunchDaemons/homebrew.mxcl.dnsmasq.plist > /dev/null 2>&1
  pwait dnsmasq start
}

dnsstatus()
{
  # Get info about running dnsmasq processes
  ps -axo user,pid,start,etime,time,nice,vsz,rss,command |\
    egrep '^USER|dnsmasq' | sed '/grep/d'
}

case $action in
  "start")
    dnsstart
    ;;
  "stop")
    dnsstop
    ;;
  "restart")
    dnsrestart
    ;;
  "status")
    dnsstatus
    ;;
  *)
    # Should never happen ...
    error_exit "Invalid action ..."
    ;;
esac

exit 0

The following shows how to start up dnsmasq with the dnsctl shell script:

$ dnsctl
Usage: dnsctl start|stop|restart|status

$ dnsctl start
Password:
dnsmasq started OK ...

$ dnsctl status 
USER               PID STARTED     ELAPSED      TIME NI      VSZ    RSS COMMAND
nobody           37845  3:16PM       00:10   0:00.01  0  4427444   1060 /usr/local/opt/dnsmasq/sbin/dnsmasq --keep-in-foreground -C /usr/local/etc/dnsmasq.conf -7 /usr/local/etc/dnsmasq.d,*.conf

$ ping -c1 anydoman.tst
PING anydoman.tst (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.025 ms

--- anydoman.tst ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.025/0.025/0.025/0.000 ms

Try it out! You can ping any domain that you can dream of (if it ends in .tst). The dnsctl script doesn’t change file permissions like the sudo brew services … command will do (when using sudo). Also, dnsutl tries to verify that the service successfully started (or stopped). I have seen cases where the brew services command said that the service started, but it actually didn’t (or died right away).

Enhanced Dnsmasq Configuration

All of the above is still good. However, I learned that there are certain applications, such as the WordPress Site Health check, that do not work with the resolver that we set up at /etc/resolver/tst. The WordPress Site Health check will report critical errors that are failing with this error:

Error: cURL error 6: Could not resolve: yourdomain.tst (Domain name not found) (http_request_failed)

I learned that this error is coming from the brew-installed curl-openssl program. You may not have WordPress installed. Another way to reproduce this issue is with the built-in host command:

$ host altoplace.tst         
Host altoplace.tst not found: 3(NXDOMAIN)

$ ping -c1 altoplace.tst
PING altoplace.tst (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.021 ms

--- altoplace.tst ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.021/0.021/0.021/0.000 ms

The host command fails, but the ping command still works. There is a simple solution. We need to update the MacOS Network DNS setting to add the dnsmasq server IP, which is 127.0.0.1. This can be done through MacOS System Preferences Network panel (click on Advanced... and then the DNS tab). However, we can use the command line to easily change the MacOS DNS setting:

networksetup -setdnsservers Ethernet 127.0.0.1 192.168.1.1
networksetup -setdnsservers Wi-Fi 127.0.0.1 192.168.1.1

A couple of comments. The 127.0.0.1 address must be first. The second address(es) should be a list of your current DNS addresses. You can look at the Network Panel before executing the above commands to determine what those addresses are. If the address is grayed-out, as it was in my case, it means that the DNS address was automatically setup by the DHCP service. You only need to execute the above command for the network interfaces that you are using. In my case, I have setup both Ethernet and Wi-Fi (defaults to using Ethernet).

Now, you can try the same host command and see that the issue is resolved:

$ host altoplace.tst                                        
altoplace.tst has address 127.0.0.1

Also, with this updated configuration, DNS queries are now being cached by dnsmasq:

$ dig +noall +stats altoplace.net
;; Query time: 53 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Thu May 13 15:31:07 CDT 2021
;; MSG SIZE  rcvd: 58

$ dig +noall +stats altoplace.net
;; Query time: 0 msec
;; SERVER: 127.0.0.1#53(127.0.0.1)
;; WHEN: Thu May 13 15:31:17 CDT 2021
;; MSG SIZE  rcvd: 58

Note that the second Query time is 0 msec. It’s not a big savings, but I guess that it might add up over time. Anyway, the critical WordPress Site Health check issues are resolved. And a final note, if you do make this network DNS update, the /etc/resolver/tst file is no longer needed and can be safely removed.

Creating our First Virtual Host

We first need to make some additional changes to our Apache configuration file and restart Apache:

$ cd /usr/local/etc/httpd

$ vi httpd.conf

$ diff ~/orig/usr/local/etc/httpd/httpd.conf .
 o o o
175c175
< #LoadModule vhost_alias_module lib/httpd/modules/mod_vhost_alias.so
---
> LoadModule vhost_alias_module lib/httpd/modules/mod_vhost_alias.so
182c182
< #LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so
---
> LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so
 o o o
507c514
< #Include /usr/local/etc/httpd/extra/httpd-vhosts.conf
---
> Include /usr/local/etc/httpd/extra/httpd-vhosts.conf

The above configuration changes enable the vhosts module and, while we were at it, the rewrite module. Now, we can add our virtual hosts to httpd-vhosts.conf:

$ cd /usr/local/etc/httpd/extra

$ vi httpd-vhosts.conf

# Delete the example virtual hosts and add:

<VirtualHost *:80>
    DocumentRoot "/Users/george/Sites"
    ServerName localhost
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/Users/george/Sites/altoplace.tst"
    ServerName altoplace.tst
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/Users/george/Sites"
    ServerName imac1.local
</VirtualHost>

Check you configuration changes:

$ apachectl configtest 
Syntax OK

# Restart Apache
# a2ctl may prompt for your system password depending on the
# last time you used sudo ...

$ a2ctl restart
httpd stopped OK ...
httpd started OK ...

Let me try to explain my changes. Since we turned on virtual hosts, I added our top-level ~/Sites directory as a virtual host. I defined my new altoplace.tst virtual host. And I added a special virtual host, imac1.local, to my vhosts file. The imac1.local domain is my Mac domain that is reachable from any system on my local network. It also points to my top-level ~/Sites directory. You can now add an index.html file and a info.php file to your new vhost directory (e.g., ~/Sites/altoplace.tst) and test that your new Virtual Host is working (http://altoplace.tst ).

Setting up SSL (TLS)

SSL is the last topic that I am going to discuss in this post. It adds the ability to test SSL enabled virtual hosts (e.g., https://altoplace.tst ). This is an important topic since the use of SSL is highly encouraged and is inexpensive to do. These days, you will see a new term, TLS, replacing SSL. You can read about SSL/TLS at the SSL link that I just provided. They are both protocols for establishing authenticated and encrypted links between networked computers.

Updating httpd.conf and extra/httpd-ssl.conf to support SSL

We just need to make a few more changes to our Apache httpd.conf and extra/httpd-ssl.conf configuration files to support the use of SSL:

# Update httpd.conf ...

$ diff ~/orig/usr/local/etc/httpd/httpd.conf .
 o o o
92c92
< #LoadModule socache_shmcb_module lib/httpd/modules/mod_socache_shmcb.so
---
> LoadModule socache_shmcb_module lib/httpd/modules/mod_socache_shmcb.so
 o o o
150c150
< #LoadModule ssl_module lib/httpd/modules/mod_ssl.so
---
> LoadModule ssl_module lib/httpd/modules/mod_ssl.so
 o o o
524c531
< #Include /usr/local/etc/httpd/extra/httpd-ssl.conf
---
> Include /usr/local/etc/httpd/extra/httpd-ssl.conf

# Update extra/httpd-ssl.conf ...

$ cd /usr/local/etc/httpd/extra               

$ cp httpd-ssl.conf ~/orig/usr/local/etc/httpd/extra

$ vi httpd-ssl.conf

$ diff ~/orig/usr/local/etc/httpd/extra/httpd-ssl.conf .
36c36
< Listen 8443
---
> Listen 443
121c121
< <VirtualHost _default_:8443>
---
> <VirtualHost _default_:443>
124,125c124,125
< DocumentRoot "/usr/local/var/www"
< ServerName www.example.com:8443
---
> #DocumentRoot "/usr/local/var/www"
> #ServerName www.example.com:8443
144c144
< SSLCertificateFile "/usr/local/etc/httpd/server.crt"
---
> SSLCertificateFile "/usr/local/etc/httpd/ssl/localhost+2.pem"
154c154
< SSLCertificateKeyFile "/usr/local/etc/httpd/server.key"
---
> SSLCertificateKeyFile "/usr/local/etc/httpd/ssl/localhost+2-key.pem"

We just uncommented two LoadModule lines to enable SSL. We also uncommented and updated the httpd-ssl.conf include file (don’t try to restart Apache yet). We changed the Homebrew defined SSL port number (8443) back to the default SSL port number (443). We still need to create the SSL certificate and key files before restarting Apache.

Updating our Virtual Hosts to use SSL

We need to update our Virtual Hosts configuration to add SSL-enabled virtual hosts to our Apache configuration:

$ cd /usr/local/etc/httpd/extra

$ vi httpd-vhosts.conf

# Add the following ...

<VirtualHost *:443>
    DocumentRoot "/Users/george/Sites"
    ServerName localhost
    SSLEngine on
    SSLCertificateFile "/usr/local/etc/httpd/ssl/localhost+2.pem"
    SSLCertificateKeyFile "/usr/local/etc/httpd/ssl/localhost+2-key.pem"
</VirtualHost>

<VirtualHost *:443>
    DocumentRoot "/Users/george/Sites"
    ServerName imac1.local
    SSLEngine on
    SSLCertificateFile "/usr/local/etc/httpd/ssl/imac1.local.pem"
    SSLCertificateKeyFile "/usr/local/etc/httpd/ssl/imac1.local-key.pem"
</VirtualHost>

<VirtualHost *:443>
    DocumentRoot "/Users/george/Sites/altoplace.tst"
    ServerName altoplace.tst
    SSLEngine on
    SSLCertificateFile "/usr/local/etc/httpd/ssl/altoplace.tst.pem"
    SSLCertificateKeyFile "/usr/local/etc/httpd/ssl/altoplace.tst-key.pem"
</VirtualHost>

Again, we still are not ready to restart Apache. We will now create the local SSL certificate and key files referenced in the httpd-vhosts.conf and extra/httpd-ssl.conf files.

Creating the local SSL certificates and keys

We could use OpenSSL to create a self-signed certificate. But instead, we are going to use mkcert to create our SSL certificates. It is very easy to use to create locally trusted development certificates. We can use Homebrew to install mkcert. Here’s how to install and use mkcert:

$ brew install mkcert nss

$ mkcert -install                                           
Created a new local CA 💥
Sudo password:
The local CA is now installed in the system trust store! ⚡️
The local CA is now installed in the Firefox trust store (requires browser restart)! 🦊

$ cd /usr/local/etc/httpd

$ mkdir ssl

$ cd ssl

$ mkcert localhost 127.0.0.1 ::1

Created a new certificate valid for the following names 📜
 - "localhost"
 - "127.0.0.1"
 - "::1"

The certificate is at "./localhost+2.pem" and the key at "./localhost+2-key.pem"
It will expire on 13 August 2023 🗓

$ mkcert altoplace.tst

Created a new certificate valid for the following names 📜
 - "altoplace.tst"

The certificate is at "./altoplace.tst.pem" and the key at "./altoplace.tst-key.pem"
It will expire on 13 August 2023 🗓

$ mkcert imac1.local

Created a new certificate valid for the following names 📜
 - "imac1.local"

The certificate is at "./imac1.local.pem" and the key at "./imac1.local-key.pem"
It will expire on 13 August 2023 🗓

The nss formal provides libraries that Firefox needs for using SSL. We ran mkcert -install one time to install a locally trusted certificate in our system trust store. Then we created a certificate for localhost. The last two examples shows how easy it is to create additional certificates for locally hosted domains. Of course, you will use your own local development domains. At this point, you are ready to restart Apache and test your newly SSL-enabled domains. I would suggest running the Apache configuration test first just to verify that you didn’t make any configuration errors. I certainly did find errors the first time around:

$ apachectl configtest                                  
Syntax OK

$ a2ctl restart
Password:
httpd stopped OK ...
httpd started OK ...

# Now test your SSL URLs:

# https://localhost
# https://imac1.local
# https://altoplace.tst

We ran the Apache configuration test, restarted Apache, and for good measure, we verified that our httpd processes were running (and had just started). If you encounter any errors, be sure to check your Apache error log (/usr/local/var/log/httpd/error_log).

Final Thoughts

At this point, you should have a basic Apache/PHP-FPM working environment, supporting SSL-enabled virtual hosts. You can start testing website environments, such as Grav or Hugo , that don’t require a MySQL database. I will write a different post about setting up MySQL to complete our local development LAMP stack (but for the Mac instead of Linux) environment. Then I will write about how I installed WordPress using WP-CLI . All coming later. Please stay tuned …

Menu