vue3 + vite + nginx + docker部署重定向问题
问题描述:
访问http://localhost:8080/web 跳转到了 http://localhost/web/
nginx配置如下:
server {
listen 80;
listen [::]:80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
location /web {
root /usr/share/nginx/html/;
index index.html index.htm;
try_files $uri $uri/ /web/index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
location /api/ {
proxy_pass http://172.17.0.1:7081/;
}
}
vue-router配置:
export const router = createRouter({
history: createWebHashHistory('/web/'),
routes,
scrollBehavior: () => ({ left: 0, top: 0 }),
})
setupPageGuard(router)
export async function setupRouter(app: App) {
app.use(router)
await router.isReady()
}
端口映射:宿主机8080 到 docker的80
原因
应用级别的重定向:如果背后有应用服务器(如 Node.js,Tomcat 等)在处理请求,那么这可能是应用级别的重定向行为,而不是 Nginx。应用服务器可能检查请求的 URL,并基于其内部逻辑进行重定向。
因为node也即docker内部的端口是80,而映射宿主机的端口为8080,导致访问http://localhost:8080/web的时候,node内部执行了重定向到http://localhost/web/(此处的端口猜测应该是用node内部的,也即80)。
解决方案
宿主机和docker都用同一端口。
可能有其他原因或解决方案,暂时未知。