使用 curl 获取 URL 的重定向目标

syn*_*gma 25 url curl

我想检查单个 URL 重定向的位置。一个例子是来自谷歌搜索结果页面的链接(点击总是通过谷歌服务器)。

我可以这样做curl吗?

ism*_*ail 22

还有一种更简单的方法

curl -w "%{url_effective}\n" -I -L -s -S $URL -o /dev/null
Run Code Online (Sandbox Code Playgroud)

它会打印

http://raspberrypi.stackexchange.com/questions/1508/how-do-i-access-the-distributions-name-on-the-command-line/1521
Run Code Online (Sandbox Code Playgroud)

网址

http://raspberrypi.stackexchange.com/a/1521/86
Run Code Online (Sandbox Code Playgroud)

  • 但是,这会占用更多的时间和带宽,因为您还要下载第二页。 (3认同)
  • @unhammer你是对的,更新了我的答案以仅执行头部请求。 (2认同)

Ale*_*ain 19

尝试这个:

$ LOCATION=`curl -I http://raspberrypi.stackexchange.com/a/1521/86 | perl -n -e '/^Location: (.*)$/ && print "$1\n"'`
$ echo "$LOCATION"
/questions/1508/how-do-i-access-the-distributions-name-on-the-command-line/1521#1521
Run Code Online (Sandbox Code Playgroud)

谷歌重定向

Google 重定向 URL 略有不同。他们返回一个 Javascript 重定向,可以很容易地处理,但为什么不处理原始 URL 和 go curl 一起呢?

$ URL="http://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CFAQFjAA&url=http%3A%2F%2Fwww.raspberrypi.org%2F&ei=rv8oUODIIMvKswa4xoHQAg&usg=AFQjCNEBMoebclm0Gk0LCZIStJbF04U1cQ"
$ LOCATION=`echo "$URL" | perl -n -e '/url=([a-zA-Z0-9%\.]*)/ && print "$1\n"'`
$ echo "$LOCATION"
http%3A%2F%2Fwww.raspberrypi.org%2F
$ echo "$LOCATION" | perl -pe 's/%([0-9a-f]{2})/sprintf("%s", pack("H2",$1))/eig'
http://www.raspberrypi.org/
Run Code Online (Sandbox Code Playgroud)

参考

  1. 对于网址解码...


sch*_*jos 8

curl可以配置为跟随重定向并在完成后打印变量。因此,您可以使用以下命令来实现您的要求:

curl -Ls -w %{url_effective} -o /dev/null https://google.com
Run Code Online (Sandbox Code Playgroud)

手册页解释了必要的参数,如下所示:

-L, --location          Follow redirects (H)
-s, --silent            Silent mode (don't output anything)
-w, --write-out FORMAT  Use output FORMAT after completion
-o, --output FILE       Write to FILE instead of stdout
Run Code Online (Sandbox Code Playgroud)


use*_*332 5

或者试试这个

curl -s -o /dev/null -I -w "HTTP_CODE: %{http_code}\nREDIRECT_URL: %{redirect_url}\n" http://raspberrypi.stackexchange.com/a/1521/86
Run Code Online (Sandbox Code Playgroud)