nginx服务器配置React的Browser路由模式,并避免出现404

前言

React路由模式分为两种:javascript

hashHistory:html

好比 http://localhost:8080/#/loginjava

browserHistoryreact

好比 http://localhost:8080/loginwebpack

browserHistory的好处大于hashHistory, 可是麻烦的地方就是,browserHistory路由模式,须要服务器的配置:nginx

请求 http://localhost:8080/login 上的资源的时候,服务器会默认搜索当前目录下的login文件夹里的资源。可是logIn这个目录实际上是不存在的,每每在刷新浏览器的时候,会==404Not fund==;git

因此须要利用 nginx 里面的 try_files 去指定一个 fall back资源;github

一、React router配置

import React from 'react';
import { Route, Switch, BrowserRouter as Router } from 'react-router-dom';

import App from '@pages/App';

function About(props) {
    console.log('about', props);
    return <div>page: about</div>;
}

// 路由配置
const routerConfig = [
    {
        path: '/',
        component: App
    },
    {
        path: '/about',
        component: About
    }
];

function AppRouter() {
    return (
        // 只有当你的应用部署到服务器的二级目录的时候,才须要设置basename
        <Router basename="/react">
            <Switch>
                {routerConfig.map(n => {
                    return <Route path={n.path} exact component={n.component}></Route>;
                })}
            </Switch>
        </Router>
    );
}

export default AppRouter;

复制代码

我这里在服务器配置了二级目录 react 做为请求目录,因此这里的 basename 须要配置成 /react。若是你的静态资源已是在根目录是不须要设置这个的。web

启动本地服务:api

about

这个时候从首页点击跳到 about ,就能看到这种路由模式的路径了;

此时若是你刷新了浏览器,将会提示找不到about目录:

在这里插入图片描述

此时能够在webpack.config.js里面增长:

devServer {
	historyApiFallback: true
}
复制代码

webpack 里面的 historyApiFallback 使用的是connect-history-api-fallback:

重启本地服务,再次刷新正常。

关于 connect-history-api-fallback

单页应用(SPA)通常只有一个index.html, 导航的跳转都是基于HTML5 History API,当用户在越过index.html 页面直接访问这个地址或是经过浏览器的刷新按钮从新获取时,就会出现404问题;

好比 直接访问/login, /login/online,这时候越过了index.html,去查找这个地址下的文件。因为这是个一个单页应用,最终结果确定是查找失败,返回一个404错误。

这个中间件就是用来解决这个问题的

只要知足下面四个条件之一,这个中间件就会改变请求的地址,指向到默认的index.html:

1 GET请求

2 接受内容格式为text/html

3 不是一个直接的文件请求,好比路径中不带有 .

4 没有 options.rewrites 里的正则匹配

二、nginx 配置

location /react {
    alias /project/react/;
    # browserHistory模式 404问题
    try_files $uri $uri/ /react/index.html;
    index index.html;
    autoindex on;
    gzip on;
    add_header Access-Control-Allow-Origin '*';
    add_header Access-Control-Allow-Methods 'GET, POST, PUT, OPTIONS';
    add_header Access-Control-Expose-Headers 'Accept-Ranges, Content-Encoding, Content-Length, Content-Range';
  }
复制代码

autoindex on; 开启这个,输入到/react 会直接定向到index.html;

try_files 主要解决的是,若是在一些目录下找不到 index.html, 会最终有一个保底资源的路径就是 /react/index.html;

try_files $uri $uri/ /react/index.html;
复制代码

浏览器输入 http://**:6002/react/about

会先查找 http://**:6002/react/about 是否有文件about.html存在;再查找/about/下是否有文件存在,若是都不存在,启动 /react/index.html;

==try_files 增长 $uri/ 能够解决 try_filesautoindex同时存在的时候,再输入/react不会自动定向到index.html的问题==;

参考文档

  1. connect-history-api-fallback

  2. nginx ~ try_files

相关文章
相关标签/搜索