What is the Purpose of the -L Flag in Curl?
The -L
or --location
flag in curl enables automatic handling of HTTP redirects, making it follow redirect responses to their final destination.
How HTTP Redirects Work
When a server moves content to a new location, it responds with a redirect status code (typically 301, 302, 303, or 307) and includes the new URL in the Location
header. By default, curl stops at the redirect response and doesn't follow it.
Without -L Flag (Default Behavior)
# Without -L, curl stops at the redirect
curl -I http://example.com/old-page
Response:
HTTP/1.1 301 Moved Permanently
Location: http://example.com/new-page
Content-Length: 0
With -L Flag
# With -L, curl follows the redirect automatically
curl -L http://example.com/old-page
This will automatically make a second request to http://example.com/new-page
and return the final content.
Common Use Cases
1. Basic URL Following
# Follow redirects to get the final content
curl -L https://short.ly/abc123
2. Downloading Files Through Redirects
# Download a file that might be redirected
curl -L -o file.zip https://example.com/download-link
3. API Endpoints with Redirects
# Follow API redirects while preserving headers
curl -L -H "Authorization: Bearer token" https://api.example.com/endpoint
Method-Specific Behavior
GET and HEAD Requests
The -L
flag works automatically with GET and HEAD requests:
# Both will follow redirects
curl -L https://example.com
curl -L -I https://example.com # HEAD request
POST Requests
For POST requests, curl requires additional flags to follow redirects:
# POST request following all redirect types
curl -L --post301 --post302 --post303 -X POST -d "data=value" https://example.com
Explanation of POST redirect flags:
- --post301
: Follow 301 redirects with POST method
- --post302
: Follow 302 redirects with POST method
- --post303
: Follow 303 redirects (typically changes to GET)
Advanced Options
Limiting Redirect Count
# Follow maximum 5 redirects
curl -L --max-redirs 5 https://example.com
Viewing Redirect Chain
# Show all redirect steps
curl -L -v https://example.com
Preserving Original Method
# Keep POST method through all redirects
curl -L --post301 --post302 --post303 -X POST https://example.com
Security Considerations
When using -L
, be aware that:
- Redirects can lead to different domains
- Sensitive headers might be sent to unintended servers
- Infinite redirect loops are possible (use --max-redirs
to prevent)
Real-World Example
# GitHub releases often redirect to CDN URLs
curl -L -o latest-release.tar.gz https://github.com/user/repo/releases/latest/download/package.tar.gz
This command will follow the GitHub redirect to the actual CDN URL and download the file directly.
The -L
flag is essential for robust web scraping and API interactions where redirects are common.