Vue路由器,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
似乎仅重定向到索引文件.如何在VueJS应用中将myapp.com/mypath
的直接链接重定向到/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路由器,nginx和直接链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!