Apache / PHP on macOS 12+

For the most agile solution to Apache and PHP on your Mac, install both using Homebrew. To save time I recommend installing in one terminal window, and editing the configuration files in another.

Installing Apache

Start by removing built-in Apache from macOS:

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

If you get an error, it simply means your macOS version didn’t have Apache already installed and running.

If you get an error (command not found) when running the following command you’ll have to install homebrew to proceed.

Install the current Apache version:

brew install httpd

Now issue the following command to have Apache run in the background (also after Mac restarts):

brew services restart httpd

You can verify that the correct Apache installation is running:

which httpd

Which should return the Homebrew path: /opt/homebrew/bin/httpd

Install PHP

Install current version of PHP:

brew install php

The last lines of output should suggest to either run PHP in the background (with auto-relaunch on Mac restart) or foreground. For the latter:

brew services restart php

Verify that PHP is running by checking the version number:

php -v

Make Apache use PHP

Now you need to configure Apache to use the installed version of PHP. Open the httpd configuration file using nano:

nano /opt/homebrew/etc/httpd/httpd.conf

You should not be able to find any “php” strings in the file (search with CTRL+W). Locate the LoadModule section and append the following line to the bottom (change version number as needed):

LoadModule php_module /usr/local/opt/php@8.1/lib/httpd/modules/libphp.so

Now, in the same file update the following by finding the striken out text and replacing it with the line directly under (replace xxxx with your user’s home directory):

Listen 8080
Listen 80

DocumentRoot "/usr/local/var/www"
DocumentRoot "/Users/xxxx/Sites"

<Directory "/usr/local/var/www"">
<Directory "/Users/xxxx/Sites">

User _www
User xxxx

Group _www
Group xxxx

#ServerName www.example.com:8080
ServerName localhost

#LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so
LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so

DirectoryIndex index.html
DirectoryIndex index.php index.html

Also add the following block to the file before saving and closing:

<FilesMatch .php$>
    SetHandler application/x-httpd-php

Again you’ll need to restart Apache for the changes to take effect:

brew services restart httpd

Now both PHP and Apache should work.

Leave a comment