OS X 上配置 Apache 虚拟主机

我使用的系统是 OS X Yosemite Version 10.10.5

启动Apache

打开 terminal,输入 sudo apachectl -v,如下显示 Apache 的版本:

1
2
3
4
hxz@Mac-mini:~$ sudo apachectl -v
Password:
Server version: Apache/2.4.16 (Unix)
Server built: Jul 22 2015 21:03:09

接着输入sudo apachectl start,这样 Apache 就启动了。打开浏览器地址栏输入 http://localhost,可以看到内容为It works!的页面。其位于/Library/WebServer/Documents/下,这是 Apache 的默认根目录。

设置虚拟主机

  • 在终端运行 sudo vi /etc/apache2/httpd.conf,打开Apche的配置文件在 httpd.conf 中找到 #Include /private/etc/apache2/extra/httpd-vhosts.conf,去掉前面的,保存并退出。

  • 运行sudo apachectl restart,重启 Apache 后就开启了虚拟主机配置功能。

  • 运行sudo vi /etc/apache2/extra/httpd-vhosts.conf,配置虚拟主机了。该文件默认开启了两个作为例子的虚拟主机:

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>

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

1
2
Forbidden
You don't have permission to access /index.php on this server

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

  • 增加如下配置:
    1
    2
    3
    4
    5
    6
    <VirtualHost *:80>
    alias /Upload "/Users/hxz/workspace/ng-flow-2.6.1/samples/Upload"
    <Directory "/Users/hxz/workspace/ng-flow-2.6.1/samples/Upload">
    Require all granted
    </Directory>
    </VirtualHost>

上面这个虚拟配置的作用是:将 /Upload 的访问路径映射到 /Users/hxz/workspace/ng-flow-2.6.1/samples/Upload目录。

如果不确定自己添加的配置是否合法,可用 sudo apachectl -t 测试下,例如:

1
2
3
hxz@Mac-mini:~$ sudo apachectl -t
AH00526: Syntax error on line 36 of /private/etc/apache2/extra/httpd-vhosts.conf:
Illegal option FollowSymLinkss

有个“坑”

如果出现下面这种错误信息:

1
[Fri Oct 16 15:20:43.568523 2015] [authz_core:error] [pid 13293] [client ::1:49853] AH01630: client denied by server configuration: /Users/hxz/workspace/ng-flow-2.6.1/samples/Upload/

可能原因:apache 2.4 版本和 2.2 以前的版本,配置上有些许改动。具体 fix 方法:

</Directory> 下面的

1
2
Order allow,deny
Allow from all

修改为:

1
Require all granted

参考

彦祖老师 wechat