在 macOS 环境编辑 apache 根目录

apache 的配置文件,在目录 /etc/apache2/ 下,打开 Finder,选择 前往 – 前往文件夹,输入 /etc/apache2/

httpd.conf

1、在 /etc/apache2/ 中找到 httpd.conf 文件打开,我选择用 Sublime Text,然后找到:

1
2
3
4
<Directory />
AllowOverride none
Require all denied
</Directory>

修改为:

1
2
3
4
<Directory />
AllowOverride none
Require all granted
</Directory>

2、开启虚拟主机配置功能,搜索:

1
#Include /private/etc/apache2/extra/httpd-vhosts.conf

把前边的注释 # 号去掉,修改为:

1
Include /private/etc/apache2/extra/httpd-vhosts.conf

说明:这个目录不用更改

1
2
DocumentRoot "/Library/WebServer/Documents"
<Directory "/Library/WebServer/Documents">

httpd-vhosts.conf

1、在 /etc/apache2/extra/ 中找到 httpd-vhosts.conf 文件打开,依然选择 Sublime Text,然后看到该文件默认开启了两个作为例子的虚拟主机:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<VirtualHost *:80>
ServerAdmin webmaster@dummy-host.example.com
DocumentRoot "/usr/docs/dummy-host.example.com"
ServerName dummy-host.example.com
ErrorLog "/private/var/log/apache2/dummy-host.example.com-error_log"
CustomLog "/private/var/log/apache2/dummy-host.example.com-access_log" common
</VirtualHost>

<VirtualHost *:80>
ServerAdmin webmaster@dummy-host2.example.com
DocumentRoot "/usr/docs/dummy-host2.example.com"
ServerName dummy-host2.example.com
ErrorLog "/private/var/log/apache2/dummy-host2.example.com-error_log"
CustomLog "/private/var/log/apache2/dummy-host2.example.com-access_log" common
</VirtualHost>

而实际上,这两个虚拟主机是不存在的,在没有配置任何其他虚拟主机时,可能会导致访问 localhost 时出现如下提示:

Forbidden
You don’t have permission to access /index.php on this server

最简单的办法就是在它们每行前面加上 # ,注释掉就好了,这样既能参考又不导致其他问题。

2、增加如下配置

1
2
3
4
5
6
7
8
<VirtualHost *:80>
ServerAdmin xxx@xxx.com
DocumentRoot "目录"
ServerName Localhost
ServerAlias host
ErrorLog "/private/var/log/apache2/dummy-host.example.com-error_log"
CustomLog "/private/var/log/apache2/dummy-host.example.com-access_log" common
</VirtualHost>

保存退出,并重启 apache

1
sudo apachectl restart

3、运行 sudo vi /etc/hosts ,打开 hosts 配置文件,加入 127.0.0.1 mysites ,这样就可以配置完成 sites 虚拟主机了,可以访问 http://mysites 了,在 10.8 之前 Mac OS X 版本其内容和 http://localhost/~[用户名] 完全一致。

4、注意,记录 log 的 ErrorLog "/private/var/log/apache2/sites-error_log"也可以删掉,但记录日志其实是一个好习惯,在出现问题时可以帮助我们判断。如果保留这些log代码,一定log文件路径都是存在的,如果随便修改一个不存在的,会导致 apache 无法服务而没有错误提示,这个比较恶心。