Mac 使用 Nginx 在本地部署静态网站
安装
安装 Brew
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
安装 Nginx
brew install nginx
nginx -v
# nginx version: nginx/1.21.6
启动 Nginx
nginx
重启
nginx -s reload
配置
默认静态页面
cd /usr/local/var/www
默认配置
cat /usr/local/etc/nginx/nginx.conf
默认日志目录
cd /usr/local/var/log/nginx
新增的配置目录
cd /usr/local/etc/nginx/servers/
新增一个静态页面服务
touch static.conf
vim static.conf
server {
listen 8607;
root /Users/mazey/Web/ProjectXYZ;
index index.html;
}
配置了 History 路由模式的 SPA 页面。
server {
listen 8621;
location / {
root /Users/mazey/Web/ProjectXYZ;
index index.html;
try_files $uri /index.html;
}
}
解释 try_files
语法:
try_files file... uri
try_files
后面定义多个文件路径进行依次尝试,响应存在的第一个文件,若文件都不存在,则会响应最后一个 uri
进行内部重定向。
try_files $uri /index.html;
例如访问 http://example.com/detail
:
- 判断
/
目录下是否存在detail
文件。 - 若
detail
文件不存在则返回http://example.com/index.html
。
附录
安装 Nginx 后的 Terminal 输出。
==> Caveats
Docroot is: /usr/local/var/www
The default port has been set in /usr/local/etc/nginx/nginx.conf to 8080 so that
nginx can run without sudo.
nginx will load all files in /usr/local/etc/nginx/servers/.
To restart nginx after an upgrade:
brew services restart nginx
Or, if you don't want/need a background service you can just run:
/usr/local/opt/nginx/bin/nginx -g daemon off;
==> Summary
🍺 /usr/local/Cellar/nginx/1.21.6_1: 26 files, 2.2MB
==> Running `brew cleanup nginx`...
Disable this behaviour by setting HOMEBREW_NO_INSTALL_CLEANUP.
Hide these hints with HOMEBREW_NO_ENV_HINTS (see `man brew`).
==> Caveats
==> nginx
Docroot is: /usr/local/var/www
The default port has been set in /usr/local/etc/nginx/nginx.conf to 8080 so that
nginx can run without sudo.
nginx will load all files in /usr/local/etc/nginx/servers/.
To restart nginx after an upgrade:
brew services restart nginx
Or, if you don't want/need a background service you can just run:
/usr/local/opt/nginx/bin/nginx -g daemon off;
参考
- Module ngx_http_core_module - try_files
- react/vue-router在history mode下,nginx所需配置 & try_files & root 、alias详解
- 【nginx】History模式的配置细节
版权声明
本博客所有的原创文章,作者皆保留版权。转载必须包含本声明,保持本文完整,并以超链接形式注明作者后除和本文原始地址:https://blog.mazey.net/2851.html
(完)
GitHub: https://github.com/mazeyqian
Blog: https://blog.mazey.net/
Blog: https://blog.mazey.net/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构