HTTP 3XX重定向时对URL Hash(Fragment identifier)的处理方式

发布 : 2019-07-23 浏览 :

项目用的Vue-Router, 路由的形式是使用 Hash History, 即 #/XXX 这种形式的, 在进入系统时如果发现没有登录, 后台会302 到 SSO用户中心,同时后台拿到登录前的页面地址进行加密编码, 以参数的形式放在302的地址中,在登录之后再302到改地址。
发现后台在探测到没有登录的时候拿到的当前页面的地址是不包含 URL Hash的, 如果不包含的话那么登录之后就可能无法重定向到登录之前的页面, 因为在302的时候URL Hash可能已经丢失了, 但是实际效果呢?
要先说明的一点是我们的用户中心是有两个版本的, 一个版本前端页面用的是JSP的, 另一个版本的做了前后端分离,只针对部分用户开放, 用的也是Vue-Router
两个版本的URL形式大概是这样的

1
2
3
4
// 旧版
http://XXXXX.com/sso/v1/login
// 新版
http://XXXXX.com/sso/v2/#/login

结果发现旧版的是能够正常跳转到登录前的页面, 而新版的URL Hash会完全丢失,
这是怎么回事呢?


http://www.w3.org/TR/cuap#uri ) 这里看到这样的规范

1
2
3
4
5
6
7
8
9
10
4.1 Handle the fragment identifier of a URI when the HTTP request is redirected.
When a resource (URI1) has moved, an HTTP redirect can indicate its new location (URI2).
If URI1 has a fragment identifier #frag, then the new target that the user agent should be trying to reach would be URI2#frag. If URI2 already has a fragment identifier, then #frag must not be appended and the new target is URI2.
Wrong: Most current user agents do implement HTTP redirects but do not append the fragment identifier to the new URI, which generally confuses the user because they end up with the wrong resource.
References:
HTTP redirects are described in section 10.3 of the HTTP/1.1 specification [RFC2616].
The required behavior is described in detail in "Handling of fragment identifiers in redirected URLs" [RURL].
The term "Persistent Uniform Resource Locator (PURL)" designates a URL (a special case of a URI) that points to another one through an HTTP redirect. For more information, refer to "Persistent Uniform Resource Locators" [PURL].
Example:
Suppose that a user requests the resource at http://www.w3.org/TR/WD-ruby/#changes and the server redirects the user agent to http://www.w3.org/TR/ruby/. Before fetching that latter URI, the browser should append the fragment identifier #changes to it: http://www.w3.org/TR/ruby/#changes.

以及Section 7.1.2. Location

1
If the Location value provided in a 3xx (Redirection) response does not have a fragment component, a user agent MUST process the redirection as if the value inherits the fragment component of the URI reference used to generate the request target (i.e., the redirection inherits the original reference's fragment, if any).

如果302的地址中已经包含了URL Hash的话,302之前页面的Hash就会被丢弃, 如果302的地址中不包含URL Hash的话浏览器就会尝试往地址中追加 URL Hash
所以实际上旧版302之后浏览器的地址会是

1
http://XXXXX.com/sso/v1/login#/XXXX

自动带了登录之前页面的路由信息, 这样在登录之后就依旧带着路由信息了。

本文作者 : Shuai Liang
原文链接 : http://liangshuai.me/2019/07/23/yuque/HTTP 3XX重定向时对URL Hash(Fragment identifier)的处理方式/
版权声明 : 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明出处!

知识 & 情怀 | 二者兼得

微信扫一扫, 向我投食

微信扫一扫, 向我投食

支付宝扫一扫, 向我投食

支付宝扫一扫, 向我投食

留下足迹