python - python 2.7不向nginx发送主机头
问题描述
我声明我的标题:
headers = {
"Host": "somehost.somedomain.com",
"Authorization": "Basic %s" % base64.b64encode(authorization)
}
然后调用我的网址:
conn = httplib.HTTPSConnection(host_name, 443, timeout=timeout, context=ssl._create_unverified_context())
conn.timeout = timeout
conn.request("GET", url, "", headers)
授权有效,但在我的 nginx 日志中,我看到 server_name 为空白
{ "@timestamp": "2019-01-21T10:32:40+00:00", "client": "172.19.0.1", "server_name": "_", "server_port": "443",
如果我做一个 curl -H 它可以工作
curl -H "Host: somehost.somedomain.com"
{ "@timestamp": "2019-01-21T10:32:21+00:00", "client": "172.19.0.1", "server_name": "somehost.somedomain.com", "server_port": "443",
解决方案
我猜你在Host
Python 代码之外的其他地方丢失了标题,它看起来正确并且为我做了正确的事情
解决几个问题并将其变成一个工作示例:
from base64 import b64encode
from httplib import HTTPSConnection
import ssl
authorization = b"user:pass"
headers = {
"Host": "somehost.somedomain.com",
"Authorization": "Basic %s" % b64encode(authorization)
}
conn = HTTPSConnection(
'www.google.com', 443, timeout=30,
context=ssl._create_unverified_context())
conn.set_debuglevel(1)
conn.request("GET", "/", None, headers)
resp = conn.getresponse()
print resp.status, resp.reason
conn.close()
注意:我借此机会将body
参数request
替换None
为它所识别的参数——你传递的是一个空字符串,它是一个空的主体而不是没有主体。
导致库在运行时将set_debuglevel
协议级别输出转储到控制台,因此它产生如下输出:
send: 'GET / HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: somehost.somedomain.com\r\nAuthorization: Basic dXNlcjpwYXNz\r\n\r\n'
reply: 'HTTP/1.1 404 Not Found\r\n'
header: Content-Type: text/html; charset=UTF-8
header: Referrer-Policy: no-referrer
header: Content-Length: 1561
header: Date: Mon, 21 Jan 2019 11:50:28 GMT
header: Alt-Svc: quic=":443"; ma=2592000; v="44,43,39,35"
404 Not Found
请注意,此响应来自谷歌,这显然失败了,因此404 Not Found
又回来了。
您可以从该send:
行中看到它正在发送适当的Host
标头。
推荐阅读
- c++ - C2011 "..." : 'class' 类型重定义问题 C++
- apache-spark - Spark 流中的 HBase 问题
- python - 如何在for循环的一行中放置多个数字
- docker - GKE 节点无法访问托管在同一 GKE 集群上的外部 IP
- c++ - 在哪里可以找到标准 C++17 cmath 文件?
- python - python列表理解不能正常工作
- excel - 尝试根据定义的标准将数据从一张表中提取到另一张表中
- wordpress - phpcs svg 转义功能 wordpress
- entity-framework - 我的日志表应该由实体框架管理吗?
- r - 编织 R Markdown 文件时出现问题 - 变量无法识别