emikulic / darkhttpd

When you need a web server in a hurry.
https://unix4lyfe.org/darkhttpd/
ISC License
1.03k stars 83 forks source link

Redirect to HTTPS if X-Forward-Proto is https #13

Closed FragmentedCurve closed 3 years ago

FragmentedCurve commented 3 years ago

If darkhttpd is running behind a reverse proxy (such as in Heroku), it might be useful to redirect to HTTPS if the client initially used HTTP.

If we run darkhttpd by doing ./darkhttpd . --daemon --forward-https --auth test:test, we get the following functionality:

$ curl -i -H 'X-Forwarded-Proto: http' 'http://localhost:8080/'
HTTP/1.1 301 Moved Permanently
Date: Wed, 18 Aug 2021 06:30:51 GMT
Server: darkhttpd/1.13.from.git
Location: https://localhost:8080/
Keep-Alive: timeout=30
Content-Length: 251
Content-Type: text/html; charset=UTF-8

<html><head><title>301 Moved Permanently</title></head><body>
<h1>Moved Permanently</h1>
Moved to: <a href="https://localhost:8080/">https://localhost:8080/</a>
<hr>
Generated by darkhttpd/1.13.from.git on Wed, 18 Aug 2021 06:30:51 GMT
</body></html>

$ curl -i -H 'X-Forwarded-Proto: https' 'http://localhost:8080/'
HTTP/1.1 401 Unauthorized
Date: Wed, 18 Aug 2021 06:30:54 GMT
Server: darkhttpd/1.13.from.git
Accept-Ranges: bytes
Keep-Alive: timeout=30
Content-Length: 211
Content-Type: text/html; charset=UTF-8
WWW-Authenticate: Basic realm="User Visible Realm"

<html><head><title>401 Unauthorized</title></head><body>
<h1>Unauthorized</h1>
Access denied due to invalid credentials.
<hr>
Generated by darkhttpd/1.13.from.git on Wed, 18 Aug 2021 06:30:54 GMT
</body></html>

$ curl -i -H 'X-Forwarded-Proto: https' 'http://test:test@localhost:8080/'
HTTP/1.1 200 OK
Date: Wed, 18 Aug 2021 06:31:02 GMT
Server: darkhttpd/1.13.from.git
Accept-Ranges: bytes
Keep-Alive: timeout=30
Content-Length: 676
Content-Type: text/html; charset=UTF-8

<html>
<head>
<title>/</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>/</h1>
<tt><pre>
<a href="..">..</a>/
<a href=".git">.git</a>/
<a href=".gitignore">.gitignore</a>         10
<a href="COPYING">COPYING</a>           694
<a href="Dockerfile">Dockerfile</a>        313
<a href="Makefile">Makefile</a>          376
<a href="README.md">README.md</a>        3394
<a href="TODO">TODO</a>               54
<a href="darkhttpd">darkhttpd</a>       52136
<a href="darkhttpd.c">darkhttpd.c</a>     88581
<a href="devel">devel</a>/
</pre></tt>
<hr>
Generated by darkhttpd/1.13.from.git on Wed, 18 Aug 2021 06:31:02 GMT
</body>
</html>