[小ネタ]curl で3xxの時にリダイレクトする


# -L オプションを付けないとリダイレクトしない
$curl -v
* Rebuilt URL to:
*   Trying
* Connected to ( port 443 (#0)
* Initializing NSS with certpath: sql:/etc/pki/nssdb
*   CAfile: /etc/pki/tls/certs/ca-bundle.crt
  CApath: none
* SSL connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
* Server certificate:
*       subject: CN=*,O=Google Inc,L=Mountain View,ST=California,C=US
*       start date:  9月 13 17:11:49 2017 GMT
*       expire date: 12月 06 17:09:00 2017 GMT
*       common name: *
*       issuer: CN=Google Internet Authority G2,O=Google Inc,C=US
> GET / HTTP/1.1
> User-Agent: curl/7.40.0
> Host:
> Accept: */*
< HTTP/1.1 301 Moved Permanently
< Location:
< Content-Type: text/html; charset=UTF-8
< Date: Sun, 01 Oct 2017 12:20:42 GMT
< Expires: Tue, 31 Oct 2017 12:20:42 GMT
< Cache-Control: public, max-age=2592000
< Server: gws
< Content-Length: 222
< X-XSS-Protection: 1; mode=block
< X-Frame-Options: SAMEORIGIN
< Alt-Svc: quic=":443"; ma=2592000; v="39,38,37,35"
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<H1>301 Moved</H1>
The document has moved
<A HREF="">here</A>.
* Connection #0 to host left intact

# -Lオプション付与でリダイレクト
$curl -L

なお、man curlを見ると以下のように記載されていました。

       -L, --location
              (HTTP/HTTPS)  If  the server reports that the requested page has
              moved to a different location (indicated with a Location: header
              and  a  3XX  response code), this option will make curl redo the
              request on the new place. If used together with -i, --include or
              -I, --head, headers from all requested pages will be shown. When
              authentication is used, curl only sends its credentials  to  the
              initial  host.  If a redirect takes curl to a different host, it
              won't be able to intercept the user+password. See  also  --loca‐
              tion-trusted  on how to change this. You can limit the amount of
              redirects to follow by using the --max-redirs option.

              When curl follows a redirect and the request is not a plain  GET
              (for example POST or PUT), it will do the following request with
              a GET if the HTTP response was 301, 302, or 303. If the response
              code  was  any  other  3xx code, curl will re-send the following
              request using the same unmodified method.

              You can tell curl to not change the non-GET  request  method  to
              GET  after  a  30x  response  by using the dedicated options for
              that: --post301, --post302 and -post303.