04 September 2013

对于OS X 10.8之前的Mac系统,可以通过共享设置里的“Web共享”开启Apache服务器。但是从10.8 Mountain Lion开始,该设置选项被去掉了 (或许苹果公司认为普通用户不应该需要这个东西)。为了将OS X 10.8 Mountain Lion作为网站服务器,必须通过命令行进行配置。

首先,用以下命令控制apache服务器的启动、停止和重启。

sudo apachectl start
sudo apachectl stop
sudo apachectl restart

启动apache以后,直接访问http://localhost,可以看到”It works!”了。

这时访问的是/Library/WebServer/Documents/文件夹中的index.html。因为在/private/etc/apache2/httpd.conf 中如下指定了Web服务的文档根目录。

#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
DocumentRoot "/Library/WebServer/Documents"

/private/etc/apache2/httpd.conf是apache的主配置文件(Linux系统中这个文件一般在/etc/apache2/中,OS X将/etc/apache2/符号链接到了/private/etc/apache2/)。 在主配置文件末尾,包含进了一些子配置文件。其中一个是:

# User home directories
Include /private/etc/apache2/extra/httpd-userdir.conf

这个子配置文件用于指定各个用户的网站目录。其中有两个方面的信息:

其一,指定用户主目录中的Sites文件夹作为站点目录,如下。

#
# UserDir: The name of the directory that is appended onto a user's home
# directory if a ~user request is received.  Note that you must also set
# the default access control for these directories, as in the example below.
#
UserDir Sites

其二,进一步包含子配置文件,允许对每个用户分别进行配置。

Include /private/etc/apache2/users/*.conf

我的用户名是shengbin。我一方面在我的主目录中新建了Sites文件夹,另一方面创建了/private/etc/apache2/users/shengbin.conf并写入如下内容:

<Directory "/Users/shengbin/Sites/">
	Options Indexes MultiViews
	AllowOverride None
	Order allow,deny
	Allow from all
</Directory>

这样便可以通过http://localhost/~shengbin来访问Sites文件夹中的内容。

要解析.php文件,还需配置apache加载PHP模块,即在/private/etc/apache2/httpd.conf中加入下面一行 (本来存在的这一行被注释掉了,取消注释即可):

LoadModule php5_module libexec/apache2/libphp5.so

配置完成后,在Sites文件夹下新建info.php,写入一行<?php phpinfo(); ?>,然后通过浏览器访问http://localhost/~shengbin/info.php, 看到下图所示的PHP信息则说明一切顺利。


开始享用Web服务吧!

最后,为使每次系统启动时apache随之自动启动,可执行以下命令:

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

如果想要说些什么,欢迎发邮件给我