使用 curl 请求重定向到带有锚标记的相对 URL 的 URL

jrd*_*oko 3 http redirect http-headers curl

我正在使用 curl 请求使用以下Location:行重定向到不同 URL 的 URL :

Location:/path/to/resource#name
Run Code Online (Sandbox Code Playgroud)

据我了解,根据 HTTP 规范,重定向响应中的那一行是无效的,因此整个 curl 调用失败是可以理解的(在这种情况下,响应代码为 400)。但是,使用 wget 或 Web 浏览器请求 URL 会成功呈现页面(我假设通过在重定向之前填充绝对路径或删除锚标记的启发式方法)。

有什么我可以做的让 curl 做同样的事情(做成功跟随重定向所必需的事情,即使它是“正式”格式错误的)?

编辑:更多细节。最终的响应代码是 400(不是 404 或其他)。当我做一个HEAD请求(有curl -I -L),我得到一个302 Found(有Location: /Error)重定向到500 Server Error。但是,如果我执行常规请求(没有-I选项但有-L选项),我会得到http_code(在 curl 中--write-out)的400. 因此,在这种情况下,HEAD 请求的功能似乎与标准 GET 不同。

Tom*_*son 6

据我了解,默认情况下 curl 不遵循 Location 标头。

您可以使用-L--location开关启用此类行为。像这样:

tom@slappy:~? curl -I -L http://shell/redirect.php     
HTTP/1.1 302 Found
Date: Tue, 17 Jan 2012 00:13:54 GMT
Server: Apache/2.2.17 (Ubuntu)
X-Powered-By: PHP/5.3.5-1ubuntu7.2
Location: /target.html#someAnchor
Content-Type: text/html

HTTP/1.1 200 OK
Date: Tue, 17 Jan 2012 00:13:54 GMT
Server: Apache/2.2.17 (Ubuntu)
Last-Modified: Tue, 17 Jan 2012 00:10:37 GMT
Accept-Ranges: bytes
Content-Length: 7
Content-Type: text/html
Run Code Online (Sandbox Code Playgroud)

注意:-I仅用于显示标题而不是页面内容。我使用在 Ubuntu 上运行的 curl 7.21.6 对此进行了测试。