Skip to content

Instantly share code, notes, and snippets.

@candlerb
Created February 10, 2022 17:02
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 candlerb/918d2b9cfcc0dc904594fb44ca53f831 to your computer and use it in GitHub Desktop.
Save candlerb/918d2b9cfcc0dc904594fb44ca53f831 to your computer and use it in GitHub Desktop.
Tiny standalone daemon to accept HTTP requests on port 80 and redirect client to HTTPS
package main
import (
"fmt"
"net/http"
"os"
"strings"
)
func redirect(w http.ResponseWriter, req *http.Request) {
parts := strings.SplitN(req.Host, ":", 2)
host := parts[0]
if host == "" {
w.WriteHeader(400)
w.Write([]byte("Invalid request, Host header missing"))
return
}
location := "https://" + host + req.URL.Path
w.Header().Set("Location", location)
w.WriteHeader(301)
}
func main() {
http.HandleFunc("/", redirect)
err := http.ListenAndServe(":80", nil)
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
[Unit]
Description=HTTP to HTTPS redirector
After=network-online.target multi-user.target
Wants=network-online.target
[Service]
ExecStart=/usr/local/sbin/redirector
User=nobody
AmbientCapabilities=CAP_NET_BIND_SERVICE
Restart=always
RestartSec=30
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment