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 -v
If 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 status
If Apache is not running, start it with the following command:
sudo apachectl start
Before 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.conf
Find the line that loads the PHP module, such as:
LoadModule php7_module /usr/local/opt/[email protected]/lib/httpd/modules/libphp7.so
If 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.conf
Uncomment this line to enable virtual hosts. Then edit the virtual hosts configuration file:
nano /usr/local/etc/httpd/extra/httpd-vhosts.conf
Add 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/hosts
Add the following line:
127.0.0.1 yourproject.local
Save and exit.
After all configurations are done, restart Apache to apply the changes:
sudo apachectl restart
Open 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.