vue-router、nginx 和直接链接 [英] vue-router, nginx and direct link
问题描述
我正在尝试在我的 nginx 服务器上设置 vue-router.我遇到的问题是,如果我直接在浏览器 myapp.com/mypath
中输入 url,我的路线将不起作用.
I'm trying to setup a vue-router on my nginx server. The issue I'm having is that my route doesn't work if I enter url directly to the browser myapp.com/mypath
.
我已经尝试过 vue 路由器文档中所述的服务器配置 以及关于堆栈溢出的建议类似配置.我当前的nginx位置配置如下:
I've tried server configuration as described in the vue router docs as well as suggested similar configurations on stack overflow. My current nginx location configuration as follows:
location / {
try_files $uri $uri/ /index.html;
}
location /subscribe {
proxy_pass http://127.0.0.1/subscribe // express API app
}
所做的只是将任何路径重定向到我的根组件(路径:/
)而不是 /mypath
.这确实有意义,并且 location
似乎只重定向到索引文件.如何将 myapp.com/mypath
的直接链接重定向到我的 VueJS 应用程序中的 /mypath
路由?
All that does is redirects any path to my root component (path: /
) and not /mypath
. This does make sense and location
seems to only redirect to the index file. How can I redirect direct link of myapp.com/mypath
to /mypath
route in my VueJS app?
这是我现在如何设置 vue 路由:
Here is how my vue routes setup now:
...
const routes = [
{ path: '/', component: Landing },
{ path: '/mypath', component: MyPath }
];
const router = new VueRouter({ mode: 'history', routes });
new Vue({
el: '#app',
router,
render: h => h(App)
});
推荐答案
我根据一位同事的建议找到了 1 个可能的解决方案.
I've found 1 possible solution with the suggestion from a co-worker.
我现在在 nginx 中将 URI 作为查询参数传递.所以我的配置现在是这样的:
I'm now passing URI as a query parameter in nginx. So my config is now this:
location / {
try_files $uri $uri/ /index.html?uri=$uri
}
然后在我的 VueJS 路由器配置中:
Then in my router configuration in VueJS:
const routes = [
{
path: '/',
component: Landing,
beforeEnter: (to, from, next) => {
const { uri } = to.query;
if (uri != null && uri != '/') {
next(false);
router.push(uri);
} else {
next();
}
}
}, ...
这似乎可以解决问题,尽管看起来有点狡猾.
This seems to do the trick, although looks a bit dodgy.
这篇关于vue-router、nginx 和直接链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!