设置 cURL 以使用本地虚拟主机 [英] Set cURL to use local virtual hosts
问题描述
使用 Apache 或 Ngnix 我总是创建基于真实项目的开发站点,例如 http://project1.loc
,在添加到我的 .hosts
文件后,浏览器使用没有问题.
Using Apache or Ngnix I always create development sites based on real projects such as http://project1.loc
which, after adding to my .hosts
file, the browser has no problem using.
但是,当我尝试向同一个 URL 发出 cURL 请求 (http://project1.loc/post.json
) 时,除了超时之外,我什么也没有得到.我假设 cURL 不关心我的自定义主机,而是直接访问名称服务器以获取其信息.
However, when I attempt to make a cURL request (http://project1.loc/post.json
) to that same URL I never get anything but a timeout. I'm assuming cURL doesn't care about my custom hosts and goes straight to a name server for it's info.
我该如何解决这个问题?
How can I fix this?
更新我设置了一个自定义标题HOST: http://project1.loc",现在我收到 400 个错误 - 但它们是即时所以我假设 cURL 至少使用主机文件...
UPDATE I set a custom header "HOST: http://project1.loc" and now I am getting 400 errors - but they are instantaneous so I'm assuming that cURL is at least using the hosts file...
推荐答案
实际上,curl 有一个明确的选项:--resolve
Actually, curl has an option explicitly for this: --resolve
代替 curl -H 'Host: yada.com' http://127.0.0.1/something
使用 curl --resolve 'yada.com:80:127.0.0.1' http://yada.com/something
你问有什么区别?
除其他外,这适用于 HTTPS.假设您的本地服务器有 yada.com
的证书,上面的第一个示例将失败,因为 yada.com
证书与 127.0.0.1<不匹配/code> URL 中的主机名.
Among others, this works with HTTPS. Assuming your local server has a certificate for yada.com
, the first example above will fail because the yada.com
certificate doesn't match the 127.0.0.1
hostname in the URL.
第二个示例与 HTTPS 一起正常工作.
The second example works correctly with HTTPS.
本质上,通过 -H
传递主机"标头确实会将您的主机侵入标头集,但绕过了 curl 的所有特定于主机的智能.使用 --resolve
可以利用所有适用的正常逻辑,但只是假装 DNS 查找返回了命令行选项中的数据.它就像 /etc/hosts
应该的那样工作.
In essence, passing a "Host" header via -H
does hack your Host into the header set, but bypasses all of curl's host-specific intelligence. Using --resolve
leverages all of the normal logic that applies, but simply pretends the DNS lookup returned the data in your command-line option. It works just like /etc/hosts
should.
注意 --resolve
需要一个端口号,所以对于 HTTPS,你会使用
Note --resolve
takes a port number, so for HTTPS you would use
curl --resolve 'yada.com:443:127.0.0.1' https://yada.com/something
这篇关于设置 cURL 以使用本地虚拟主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!