History Router Nginx配置完整指南

3,303 阅读1分钟

前言

在开发单页应用的时候, 如果使用History路由, 我们要保证每个可访问路径都能直接访问到index.html的内容。
本文主要讲解History路由模式下的Nginx配置。

一、Index.html存在服务器本地

这种方式应该是非常普遍的, 在VueRouter的官方文档中也提到了, 只需要配置一个location try_files默认指向index.html即可。

location / {
  add_header Cache-Control 'no-store, no-cache'; // 设置不缓存
  try_files $uri $uri/ /index.html;
}

举个🌰

基础页面Url是 https://a.b.com/main/, index.html存储在服务器的/home/dist/index.html下。

期望访问任何基础Url下的子路径, 都返回index.html, 则可如下配置:

// 配置在a.b.com域名下
location /main/ {
  try_files $uri $uri/ /home/dist/index.html;
}

二、Index.html存在远程地址

有的时候我们的index.html并不会存在于服务器本地上,而是一个远程的地址(oss/cdn), 这时候就需要先重写访问路径, 再通过proxy_pass代理到远端文件。

location ^~ /test/ {
    add_header Cache-Control 'no-store, no-cache'; // 设置不缓存
    rewrite ^ /project/index.html break;
    proxy_pass https://oss.b.com;
}

举个🌰

基础页面Url是 https://a.b.com/main/,, index.html存储在https://oss.b.com/project/index.html

期望访问任何基础Url下的子路径, 都返回index.html, 则可如下配置:

// 配置在a.b.com域名下
location /main/ {
    rewrite ^ /project/index.html break;
    proxy_pass https://oss.b.com;
}

写在最后

本文到这里就结束啦 因为看网上很少有关于远程index.html的配置, 所以写了这篇文章,希望对大家有用。 转载请注明作者和本文链接。