搭建好了php的开发环境之后,用
localhost就可以访问nginx或apache的文件根目录了,如果想用域名来访问的话,就需要设置虚拟主机了
前提
已经搭建了nginx+mysql+php+php-fpm的开发环境
编辑hosts
mac电脑上hosts文件位于/etc/hosts
终端打开hosts文件
vim /etc/hosts
编辑如下
127.0.0.1 localhost
127.0.0.1 myblog.com //设置你想要用的域名
255.255.255.255 broadcasthost
::1 localhost
设置的域名甚至可以是线上已有的域名,如baidu.com,不过这样子设置之后就不能访问线上的真实网站了
启动nginx端口监听
- 进入
nginx目录,如果你使用homebrew安装的nginx的话,那么目录是/usr/local/etc/nginx
cd /usr/local/etc/nginx
- 查看配置文件
nginx.conf确认最后一行有下面这句,没有的话就手动添加
include servers/*;
- 打开
nginx目录下的文件夹servers(如无,手动添加),新建一个server,命名为blog
cd servers
vim blog
编辑如下内容:
server {
listen 8080; //此处修改端口号
server_name myblog.com; //此处添加hosts中设置的域名
root ~/blog; //此处设置项目根目录
location ~ \.php$ { ## Execute PHP scripts
expires off; ## Do not cache dynamic content
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params; ## See /etc/nginx/fastcgi_params
}
location / {
index index.html index.php; ## Allow a static html file to be shown first
try_files $uri $uri/ @handler; ## If missing pass the URI to Magento's front handler
expires 30d; ## Assume all files are cachable
if ($request_uri ~* "\.(png|gif|jpg|jpeg|css|js|swf|ico|txt|xml|bmp|pdf|doc|docx|ppt|pptx|zip)$") {
expires max;
}
# set fastcgi settings, not allowed in the "if" block
include /usr/local/etc/nginx/fastcgi_params;
fastcgi_split_path_info ^(.+\.php)(/.+)$; #this line
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
fastcgi_param SCRIPT_NAME /index.php;
fastcgi_param MAGE_RUN_CODE default;
fastcgi_param MAGE_RUN_TYPE store;
# rewrite - if file not found, pass it to the backend
if (!-f $request_filename) {
fastcgi_pass 127.0.0.1:9000;
break;
}
}
}
然后就可以用你设置的域名和端口号(此处为jim.practise.com:8080)来访问你的项目了
若监听的是80端口那么域名后面的端口号可以省略
以后如果要使用别的域名,只需要在servers文件夹下面继续新增就可以了
补充:现代版本的虚拟主机配置
原文的 servers/*.conf 拆分思路非常好,至今依然是 nginx 配置的最佳实践。但有三处会导致今天直接起不来。
1. 配置文件里不能写 // 注释
原文的 nginx 配置块里用了 // 当注释:
listen 8080; //此处修改端口号
root ~/blog; //此处设置项目根目录
nginx 只支持 # 注释,// 会被当成语法错误,nginx -t 直接报 unexpected "/" in ...。这是原文最严重的问题。
2. root ~/blog; 不会展开 ~
nginx 不展开波浪号,它会到字面量 ~/blog 这个路径下找文件,结果是 404。必须写绝对路径:
root /Users/your-name/blog;
3. 全局的 include 写法
原文说在 nginx.conf 最后加 include servers/*;。Homebrew 装的 nginx 早已内置:
include servers/*; # 不同版本可能是 servers/*.conf
改完务必先检查再 reload:
nginx -t # 语法检查,一定能发现问题
brew services restart nginx
原文直接 nginx -s reload 而不先 -t,是很容易把自己弄到「服务停了、网站全挂」的原因——reload 失败时旧配置还在,但重启失败就真的没了。
4. 修改 hosts 的注意事项
/etc/hosts需要 sudo 编辑,且改完立即生效,无需重启。- macOS 上 DNS 缓存偶尔会导致改了 hosts 不生效,可执行
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder。 - 原文说「可以把域名设成线上已有的,如 baidu.com」——这确实是学习手段,但别在需要访问真实站点的机器上这么干,很容易忘记改回来。
5. 今天的替代方案
如果只是需要「用域名访问本地项目」,比改 hosts 更省事的做法:
dnsmasq+ 泛域名:配.test结尾的域名统一解析到 127.0.0.1,一次配置永远生效。valet(Laravel Valet):一个命令起站点,自动处理域名和 TLS,PHP 环境下非常省事。Caddy:配置文件比 nginx 短得多,自动 HTTPS,适合个人项目。
本文整理于 2016 年,2026 年 11 月补充。