1. 背景
团队的前端使用 React + React Router 开发单页应用(SPA),特别影响用户体验的一个痛点是:
- 浏览器刷新当前页面,提示 404
- 点击浏览器历史记录,提示 404
- 输入 URL,提示 404
Linux + Nginx 环境前端团队找到了解决方案,在 nginx.conf
添加如下代码即可:
location ~ /xxx/ {
if ($request_uri ~* ^([^.]+|.*\.html)$){
proxy_pass http://$proxy_ip/xxx-lk/index.html;
}
root
index /xxx/index.html;
}
location ~ /xxx-lk/ {
root
index /xxx/index.html;
}
}
即将上线的项目,客户使用 Windows 服务器,我们不得不在 IIS 完成同样的配置……
2. 路由原理
2.1. Server side
2.2. Client side
- 向服务器
发起请求,服务端路由找不到
/about
,默认返回包含所需资源的页面index.html
。 - 浏览器加载 React 和 React Router,路由初始化成功,将
/about
指向About us
组件(Component)。 - 浏览器 URL 为
,客户端路由导航显示
About us
组件,隐藏其他组件。
2.3. React Router
常用的 history 有三种形式:
- createMemoryHistory
3. 解决方案
3.1. IIS
web.config
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="React-Router" stopProcessing="true">
<match url="^xxx/(.*)" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="xxx/index.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
3.2. Nginx
nginx.conf
location /xxx {
try_files $uri $uri/ /xxx/index.html;
}