Skip to content

Instantly share code, notes, and snippets.

@attakei
Last active September 16, 2020 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save attakei/c6d4e3eb5274f3b1ff4ef539ab5fdadb to your computer and use it in GitHub Desktop.
Save attakei/c6d4e3eb5274f3b1ff4ef539ab5fdadb to your computer and use it in GitHub Desktop.
gunicorn edit header before passing wsgi

Run server

$ gunicorn main:app

Request/Response

No header

» http localhost:8000/hello/world
HTTP/1.1 200 OK
Connection: close
Content-Length: 39
Content-Type: text/html; charset=UTF-8
Date: Wed, 16 Sep 2020 16:51:30 GMT
Server: gunicorn/20.0.4

<b>Hello world from localhost:8000</b>!

With header

» http localhost:8000/hello/world x-forwarded-host:example.com
HTTP/1.1 200 OK
Connection: close
Content-Length: 39
Content-Type: text/html; charset=UTF-8
Date: Wed, 16 Sep 2020 16:52:00 GMT
Server: gunicorn/20.0.4

<b>Hello world from localhost:8000</b>!

Run server

$ gunicorn main:app -c config.py

Request/Response

No header

» http localhost:8000/hello/world
HTTP/1.1 200 OK
Connection: close
Content-Length: 39
Content-Type: text/html; charset=UTF-8
Date: Wed, 16 Sep 2020 16:53:12 GMT
Server: gunicorn/20.0.4

With header

» http localhost:8000/hello/world x-forwarded-host:example.com
HTTP/1.1 200 OK
Connection: close
Content-Length: 36
Content-Type: text/html; charset=UTF-8
Date: Wed, 16 Sep 2020 16:53:31 GMT
Server: gunicorn/20.0.4

<b>Hello world from example.com</b>!
"""Configuration
"""
forwarded_allow_ips = "*"
proxy_protocol = True
proxy_allow_ips = "*"
def pre_request(worker, req):
"""Catch x-forwarded-host
"""
xf_hosts = [h[1] for h in req.headers if h[0] == "X-FORWARDED-HOST"]
if not xf_hosts:
return
xf_host = xf_hosts[0]
headers = []
print(f"Cache X-Forwarded-Host {xf_host}")
for h in req.headers:
if h[0] != "HOST":
headers.append(h)
continue
headers.append(("HOST", xf_host))
req.headers = headers
from bottle import (
Bottle, run, request, template,
)
app = Bottle()
@app.route('/hello/<name>')
def index(name):
host = request.headers.get("Host")
return template(
'<b>Hello {{name}} from {{host}}</b>!',
name=name,
host=host,
)
if __name__ == "__main__":
run(app, host='localhost', port=8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment