vue-router、nginx 和 direct link

vue-router, nginx and direct link

我正在尝试在我的 nginx 服务器上设置一个 vue-router。我遇到的问题是,如果我直接在浏览器 myapp.com/mypath.

中输入 url,我的路线将不起作用

我已经尝试了 vue router docs 中描述的服务器配置,并在堆栈溢出时建议了类似的配置。我目前的nginx位置配置如下:

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 的直接 link 重定向到 /mypath 路由?

现在我的 vue 路由设置如下:

...
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)
});

我根据 co-worker 的建议找到了 1 个可能的解决方案。

我现在将 URI 作为 nginx 中的查询参数传递。所以我现在的配置是这样的:

location / {
    try_files $uri $uri/ /index.html?uri=$uri
}

然后在我的 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();
        }
    }
}, ...

这似乎可以解决问题,尽管看起来有点不可靠。

为了解决同样的问题,我挣扎了几个小时。 毕竟这个配置对我有用:

events {
...
  http {
  ...
    server {
          listen       80;
          server_name  localhost;

          location / {
              root   /path/to/your/project/html;
              index  index.html index.htm;
              include  /etc/nginx/mime.types;
              try_files $uri $uri/ /index.html;
          }
    }
  }
}

我的路由器设置和你差不多。

  1. 得到:/etc/nginx/sites-enabled

  2. 打开您域的配置

  3. 在'root'

    下添加如下代码
    location / {
      try_files $uri $uri/ /index.html;
    }
    
  4. 保存文件

  5. 使用命令重启你的 nginx 服务器:/etc/init.d/nginx restart

  6. 刷新浏览器

好吧,我遇到了同样的问题,所以我尝试将每一个 404 错误都重定向到根目录 url,它非常有效。

  1. 得到:/etc/nginx/sites-enabled

  2. 打开默认配置文件

  3. 在 404 重定向位置之前添加此行:

    error_page404/;

保存文件,别忘了重启nginx

您是否在 vue.conf 和 nginx 中使用自定义公共路径 (mypath)?

如果是这样,您需要更改配置以匹配该路径。

location /mypath {
    try_files $uri $uri/mypath /mypath/index.html
}

我的建议是确保按照 vue-router 文档中的建议使用下一行。 但是,此外,如果您有多个文件来设置您的 nginx 服务器,例如用于设置服务器 SSL 的文件,请确保也将其包含在这些文件中。

location / {
  try_files $uri $uri/ /index.html;
}

在我的例子中 try_files 没有工作,可能是因为另一个 nginx 在我的应用程序 nginx 上,使用 proxy_pass。我不得不使用 404 错误重写:

server {
    listen ${NGINX_PORT} ssl;
    server_name ${NGINX_HOST};
    ssl_certificate ${NGINX_SSL_CERTIFICATE};
    ssl_certificate_key ${NGINX_SSL_CERTIFICATE_KEY};
    error_page 404 =200 /index.html;
    location / {
        root ${NGINX_ROOT_LOCATION};
        index  index.html;
        include  /etc/nginx/mime.types;
    }
}