一、前因后果
项目要求从原先的hash的路由模式调整为history路由模式。
二、实现过程
当前前端进行,将其hash路由模式改为history路由模型时,原先的网站会出现404的问题。
原因是:所有的前端路由请求需要被重定向到入口文件(通常是 index.html
),而不是 index.php
,这样前端应用才能正确处理路由。
为此,我们要确保两点:
1、API 请求正确地转发到 Laravel 的入口文件 index.php
。
2、非 API 请求(即前端路由请求)重定向到前端应用的入口文件,通常是 index.html
。
所以。我们需要调整伪静态文件:.htaccess(apache)
# Handle Frontend Paths: Assume All URLs are Handled by the Frontend
# except the actual files or API requests
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !^/api
RewriteRule ^ index.html [L]
# Handle API Requests: Forward to Laravel's Front Controller
RewriteCond %{REQUEST_URI} ^/api
RewriteRule ^ index.php [L]
配置做的事情:
1、对所有非文件、非目录请求,如果它们不是 /api
的一部分,则假定它们是由前端应用处理(重写到 index.html
)。
2、对所有以 /api
开头的请求,保证它们被转发给 Laravel 的 index.php
,以便后端能够处理这些 API 请求。
三、测试结果
成功!