问题原文
原帖链接 · bdesham · CC BY-SA 3.0
I was scanning my website for links that point to HTTP 301/302/303 redirects when I found a puzzling behavior of the curl utility. Consider the output from the following three commands:
$ curl -I http://jekyllrb.com
HTTP/1.1 302 Found
Connection: close
Pragma: no-cache
cache-control: no-cache
Location: /
$ curl -I http://jekyllrb.com/
HTTP/1.1 302 Found
Connection: close
Pragma: no-cache
cache-control: no-cache
Location: /
$ curl -LI http://jekyllrb.com/
HTTP/1.1 200 OK
Server: GitHub.com
Date: Tue, 30 Dec 2014 01:31:47 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 8177
Last-Modified: Mon, 22 Dec 2014 14:17:25 GMT
Expires: Tue, 30 Dec 2014 01:41:47 GMT
Cache-Control: max-age=600
Vary: Accept-Encoding
Accept-Ranges: bytes
I understand the output from the first command: if you request the “naked” domain you will be redirected to the path “/”. But when you actually request the indicated path you seem to be redirected to the URL you just requested!
Then, when you add the -L option to tell curl to follow redirects, it looks as if you’re taken directly to the real page without any intermediate steps! (Usually when curl follows redirects it prints a set of headers for each request—if there had been an HTTP 302 in there somewhere then it should have been shown before the HTTP 200.)
Can anyone explain to me (1) why the redirect to the same URL is valid; and (2) why including the -L flag seems not to follow, but instead to completely bypass the redirect?
已采纳解答
原帖链接 · Stephen Ostermiller · CC BY-SA 3.0
Your first two requests are the same. All clients (including curl) have to send the slash after the domain name as part of the HTTP request whether or not it is on the URL. There is no way to formulate a valid HTTP request without it. A minimal HTTP request is:
GET / HTTP/1.0
host: jekyllrb.com
Omitting the slash from that will result in a "400 bad request" error.
It appears that the behavior is intermittent. Sometimes the server responds with a redirect and sometimes it does not. I've tried it dozens of times myself with curl and I occasionally get the redirect, but most of the time I do not.
Redirecting to the same URL is occasionally used to set cookies and test to see that they are set. I don't see any cookies being set on this request, but curl may retry a request that redirects to the same URL with the -L option.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
