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

相關文章
相關標籤/搜索