在Mac上设置Nginx虚拟主机
我用谷歌搜了一下,结果出来的信息都比较老,或者是介绍了一些复杂的方法,导致我走了很多弯路,但实际上做起来意外地很简单。
我的环境
Mac操作系统10.8.5(山狮)
Homebrew 0.9.5
已经安装的nginx
nginx 1.8.1 可以被改写为“NGINX版本为1.8.1”。
安装nginx
我使用Homebrew进行了安装。
$ brew install nginx
默认端口似乎设置为8080,文件路径为 /usr/local/etc/nginx/nginx.conf。
在Mac上,没有管理员权限的用户只能使用1024之后的端口,所以可能是这样设置的。
$ brew info nginx
默认端口已经设置在/usr/local/etc/nginx/nginx.conf文件中为8080,以便nginx可以在没有sudo权限的情况下运行。
请事先设定路径
$ export PATH=$PATH:/usr/local/sbin
为了预防万一,请停止Apache。
如果使用的端口不同,我想应该是可以的,但还是为了确保一下。
sudo apachectl stop
启动nginx
我們會檢查它是否正常運作。
$ nginx

停止nginx
$ nginx -s stop
虚拟主机的设置
修改nginx.conf文件。
$ cd /usr/local/etc/nginx
$ open .
由于已经在文件中写有虚拟主机配置的示例(大约在第80行),因此我们将根据此示例添加以下配置。
# another virtual host using mix of IP-, name-, and port-based configuration
server {
listen 8080; // 使用するポート
server_name test.local; // ホスト名
location / {
root /Users/megurock/Sites/test/; // ソースの保存場所
index index.html index.htm;
}
}
添加主机
我要编辑Mac的hosts文件。
$ cd /private/etc
$ open .
127.0.0.1 test.local // ホストを追加
127.0.0.1 localhost
重新启动nginx
$ nginx
访问 http://test.local:8080。
备注
如果将端口设置为80或其他低于1024的端口,则需要以管理员权限运行nginx命令。
# another virtual host using mix of IP-, name-, and port-based configuration
server {
listen 80; // 使用するポート
server_name test.local; // ホスト名
location / {
root /Users/megurock/Sites/test/; // ソースの保存場所
index index.html index.htm;
}
}
$ sudo nginx // 管理者権限でnginxを起動
你可以通过 http://test.local 进行访问。
$ sudo nginx -s stop // 管理者権限でnginxを停止
这就是我们所讨论的内容。