PHP remains a widely used server-side scripting language in modern web development. Setting up PHP virtual hosts on your Mac allows you to create a local server environment that simulates a real web server. This improves development efficiency and avoids the inconvenience of testing directly on a remote server.
First, make sure Homebrew is installed on your Mac. Homebrew is a powerful package manager for macOS. To check if it is installed, open Terminal and run:
brew -vIf it is not installed, visit the Homebrew official website and follow the installation instructions.
Mac usually comes with Apache pre-installed. You can check its status by running:
sudo apachectl statusIf Apache is not running, start it with the following command:
sudo apachectl startBefore configuring virtual hosts, ensure Apache supports PHP. Open the Apache configuration file, usually located at /usr/local/etc/httpd/httpd.conf, by running:
nano /usr/local/etc/httpd/httpd.confFind the line that loads the PHP module, such as:
LoadModule php7_module /usr/local/opt/[email protected]/lib/httpd/modules/libphp7.soIf it is commented out with a “#”, remove the hash symbol to activate it. Save and close the file.
In the Apache configuration file, locate the following line:
#Include /usr/local/etc/httpd/extra/httpd-vhosts.confUncomment this line to enable virtual hosts. Then edit the virtual hosts configuration file:
nano /usr/local/etc/httpd/extra/httpd-vhosts.confAdd the following configuration at the end of the file, replacing the paths and server name with your own project details:
DocumentRoot "/Users/your-username/Sites/your-project" ServerName yourproject.local AllowOverride All Require all granted To make your browser recognize the custom domain, add a mapping to the Hosts file by running:
sudo nano /etc/hostsAdd the following line:
127.0.0.1 yourproject.localSave and exit.
After all configurations are done, restart Apache to apply the changes:
sudo apachectl restartOpen your browser and enter the custom domain, for example, yourproject.local. If your PHP project loads correctly, the setup is successful.
Following these steps, you can quickly set up a PHP virtual host environment on your Mac, greatly improving development and debugging efficiency. This local environment setup is practical for personal projects and learning. We hope this guide helps you complete the configuration smoothly and enjoy a more efficient PHP development experience.