606

I know that in a php script:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

will follow redirects. Is there a way to follow redirects with command line cURL?

miken32
  • 42,008
  • 16
  • 111
  • 154
user1592380
  • 34,265
  • 92
  • 284
  • 515

3 Answers3

1016

Use the location header flag:

curl -L <URL>
curl --location <URL>  # or (same thing)
Gabriel Staples
  • 36,492
  • 15
  • 194
  • 265
Nathan Kuchta
  • 13,482
  • 2
  • 26
  • 35
  • 3
    This doesn't work with authenticating with Google to access the spreadsheets, either. :/ – fatuhoku May 16 '14 at 14:08
  • 25
    `man curl`: "When authentication is used, curl only sends its credentials to the initial host. <...> See also --location-trusted on how to change this." – hudolejev Oct 08 '14 at 10:52
58

As said, to follow redirects you can use the flag -L or --location:

curl -L http://www.example.com

But, if you want limit the number of redirects, add the parameter --max-redirs

--max-redirs <num>

Set maximum number of redirection-followings allowed. If -L, --location is used, this option can be used to prevent curl from following redirections "in absurdum". By default, the limit is set to 50 redirections. Set this option to -1 to make it limitless. If this option is used several times, the last one will be used.

freedev
  • 25,946
  • 8
  • 108
  • 125
29

I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.

For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>

Note that j_username and j_password is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case. After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>
William Miller
  • 9,839
  • 3
  • 25
  • 46
user3817445
  • 455
  • 6
  • 5