Created
February 10, 2022 17:02
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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