server 模块配置
listen: 80;
server_name: www.big-event.com big-event.com ; # 可配置多个域名
# 工作流程:
# 1. 浏览器发送一个请求,通过DNS解析域名,获取 IP。
# 2. 根据 IP 找到主机,记录【请求的端口号】和请求头中【host】(记录访问时的域名)的信息。
# 3. 拿着 host中的域名和请求端口 匹配 server_name 和 listen。锁定到 server 模块。
location 模块配置
1、~ # 使用波浪符“ ~”区分大小写正则匹配,如 location ~ /abc { }
2、~* #不区分大小写的正则匹配,如 location ~* /abc { }
3、^~ # 匹配路径的前缀,如果找到停止搜索,如 location ^~ /abc { }
4、= #精确匹配 如 location = /abc { }
5、 #普通路径前缀匹配 如 location /abc { }
server{
listen 80;
server_name www.big-event.com;
# 部署 vue 项目,将dist文件 放在 nginx的html目录下。
location / {
root /usr/share/nginx/html/dist; # 绝对路径
try_files $uri $uri/ $uri.html /index.html; # 解决路由 404问题
}
# 比如:
# root: nginx会拿着uri 从root指定的根目录下开始匹配。
# 1. 访问 http://www.big-event.com/js/abc.js
拿到 uri = /js/abc.js ,被location的规则 / 匹配。
然后尝试匹配 try_files中的 $uri,在 dist下有/js/abc.js,成功匹配。
# 2. 访问 http://www.big-event.com/category (Vue的路由)
拿到 uri = /category
然后尝试匹配 try_files中的 $uri,在 dist下没有/category,匹配失败。
然后尝试匹配 try_files中的 $uri/,在 dist下没有 /category/,匹配失败。
然后尝试匹配 try_files中的 $uri.html,在 dist下没有 /category.html,匹配失败。
然后尝试匹配 try_files中的 /index.html, 在 dist下有 /index.html,匹配成功,访问index.html, 然后路由到/category。
location /prod-api/ {
proxy_pass http://wuyu.love:9090/;
#如果访问路径为 http://wuyu.love:80/prod-api/admin/test
则实际访问路径为 http://wuyu.love:9090/admin/test
}
}