Contents

使用WGET下载内容时防止重定向

1. 概述

wget是用于从 Internet 下载内容的最常用工具之一。使用wget,我们可以以非交互式、自动化的方式镜像网站、下载文件和媒体等。它足够智能,可以自动跟踪超链接和 HTTP 重定向。

但是,可能存在我们不希望wget遵循重定向的情况。在本教程中,我们将了解wget对服务器重定向响应的默认行为以及如何更改此行为。

2. 使用wget下载内容

wget使用起来非常简单。假设我们要查看 Linux 内核的许可证。我们可以从它的 git repo 中获取 LICENSE 文件:

$ wget https://github.com/torvalds/linux/raw/master/LICENSES/preferred/GPL-2.0
--2022-02-03 20:39:21--  https://github.com/torvalds/linux/raw/master/LICENSES/preferred/GPL-2.0
SSL_INIT
Loaded CA certificate '/etc/ssl/certs/ca-certificates.crt'
Resolving github.com (github.com)... 13.234.210.38
Connecting to github.com (github.com)|13.234.210.38|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://raw.githubusercontent.com/torvalds/linux/master/LICENSES/preferred/GPL-2.0 [following]
--2022-02-03 20:39:22--  https://raw.githubusercontent.com/torvalds/linux/master/LICENSES/preferred/GPL-2.0
SSL_INIT
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.111.133, 185.199.109.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 18729 (18K) [text/plain]
Saving to: ‘GPL-2.0’
GPL-2.0                          100%[==============================================================>]  18.29K  --.-KB/s    in 0.003s
2022-02-03 20:39:23 (5.63 MB/s) - ‘GPL-2.0’ saved [18729/18729]

这会将内容下载到我们当前目录中名为GPL-2.0的文件中。当然,如果需要,我们可以使用-O标志更改下载文件的名称。

在这里,如果我们仔细观察上面的输出,有一行内容为*“已发送 HTTP 请求,正在等待响应……找到 302”*。这意味着我们使用的 URL 导致 HTTP 重定向到另一个 URL。

重定向 URL 在Location HTTP 响应标头中提供。在上面的示例中,我们还可以在输出的下一行中看到Location标头的值。

3. 使用wget时防止重定向

wget默认情况下遵循来自给定 URL 的重定向。但在某些情况下,我们可能希望减少重定向次数或完全阻止重定向。例如,在镜像网站时,我们可能希望防止网站中的链接重定向到外部网站。

我们可以使用wget–max-redirect**标志来做到这一点。它的默认值为 20。因此,wget将为 URL 跟踪最多 20 次重定向。如果我们将它设置为 0,它将停止跟随重定向

让我们再次尝试前面的示例,将*–max-redirect*设置为 0:

$ wget --max-redirect=0 https://github.com/torvalds/linux/raw/master/LICENSES/preferred/GPL-2.0
--2022-02-03 20:49:28--  https://github.com/torvalds/linux/raw/master/LICENSES/preferred/GPL-2.0
SSL_INIT
Loaded CA certificate '/etc/ssl/certs/ca-certificates.crt'
Resolving github.com (github.com)... 13.234.210.38
Connecting to github.com (github.com)|13.234.210.38|:443... connected.
HTTP request sent, awaiting response... 302 Found
Location: https://raw.githubusercontent.com/torvalds/linux/master/LICENSES/preferred/GPL-2.0 [following]
0 redirections exceeded.

在这里,我们可以看到wget报告“超过 0 个重定向”。之后,它停止并且不遵循Location标头中的 URL。同样,如果我们想要允许特定数量的重定向,我们可以将*–max-redirect*的值设置为所需的值。