nginx部署
项目类型 | 资源路径引用方式 | Nginx 解析方式 | 是否出问题 |
---|
原生 HTML(/t/) | 直接使用相对路径,如 ./images/logo.png | /t/images/logo.png | ✅ 不会有问题 |
Vue(/o/) | 默认使用绝对路径 /assets/index.js | Nginx 解析到 /assets/ 而不是 /o/assets/ | ❌ 会 4 |
方案 1:Vue 修改 publicPath
(推荐)
module.exports = {
publicPath: '/o/' // 让 Vue 知道资源在 /o/ 下面
};
方案 2:Nginx 修正 /assets/
访问路径
如果不想改 Vue 项目,可以让 Nginx 把 /assets/
请求指向 /o/assets/
:
如果不想改 Vue 项目,可以让 Nginx 把 /assets/ 请求指向 /o/assets/:location /assets/ {root /usr/share/nginx/html/o;
}然后 http://47.103.16.236/assets/index.js 其实访问的是:/usr/share/nginx/html/o/assets/index.js
- 纯静态 HTML 不会有问题,因为它的资源路径是相对的,不会影响 Nginx 路径解析。
- Vue 项目 会有问题,因为默认构建出的
index.html
里assets/
目录是根路径/
,导致 Nginx 找不到资源。 - 最好的做法 是 修改 Vue
publicPath
,如果不想改 Vue 项目,就 修改 Nginxlocation /assets/
。
server {listen 80; # 监听 IPv4 地址的 80 端口listen [::]:80; # 监听 IPv6 地址的 80 端口server_name localhost; # 设置服务器的主机名为 localhostroot /usr/share/nginx/html; # 设置服务器根目录为 /usr/share/nginx/html,所有请求默认从这个目录查找文件# 处理 /o/ 路径下的请求location /o/ {index index.html index.htm; # 设置默认访问文件为 index.html 或 index.htm# 注意:如果 Vue 或其他前端框架使用了 history 模式的路由,这里可能需要增加 try_files 配置}# 处理 /t/ 路径下的请求location /t/ {index index.html index.htm; # 设置默认访问文件为 index.html 或 index.htm}# 处理 /assets/ 路径下的请求location /assets/ {root /usr/share/nginx/html/o; # 设置 /assets/ 请求的根目录为 /usr/share/nginx/html/o# 这意味着 /assets/ 目录下的静态资源文件将从 /usr/share/nginx/html/o/assets/ 查找}
}