首页 > 解决方案 > 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",

标签: python

解决方案


我猜你在HostPython 代码之外的其他地方丢失了标题,它看起来正确并且为我做了正确的事情

解决几个问题并将其变成一个工作示例

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标头。


推荐阅读