配置你的域,使用CloudFlare的DNS服务器
在CloudFlare的DNS设置中,将域指向你的服务器,并通将“状态”设为“DNS和HTTP代理服务器(CDN)”
在CloudFlare的加密设置中,将SSL设为“灵活”(该选项使浏览器通过HTTPS与CloudFlare对话,CloudFlare通过HTTP与浏览器对话)
在web管理界面配置CloudFlare的HTTPS代理,提供你的服务器的IP地址。
除此之外,还要启用“总是使用HTTPS”选项
const (
htmlIndex = `Welcome!`
inProduction = true
)
func handleIndex(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, htmlIndex)
}
func makeHTTPServer() *http.Server {
mux := &http.ServeMux{}
mux.HandleFunc("/", handleIndex)
// set timeouts so that a slow or malicious client doesn't
// hold resources forever
return &http.Server{
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 120 * time.Second,
Handler: mux,
}
}
func main() {
var httpsSrv *http.Server
// when testing locally it doesn't make sense to start
// HTTPS server, so only do it in production.
// In real code, I control this with -production cmd-line flag
if inProduction {
// Note: use a sensible value for data directory
// this is where cached certificates are stored
dataDir := "."
hostPolicy := func(ctx context.Context, host string) error {
// Note: change to your real domain
allowedHost := "www.mydomain.com"
if host == allowedHost {
return nil
}
return fmt.Errorf("acme/autocert: only %s host is allowed", allowedHost)
}
httpsSrv = makeHTTPServer()
m := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: hostPolicy,
Cache: autocert.DirCache(dataDir),
}
httpsSrv.Addr = ":443"
httpsSrv.TLSConfig = &tls.Config{GetCertificate: m.GetCertificate}
go func() {
err := httpsSrv.ListenAndServeTLS("", "")
if err != nil {
log.Fatalf("httpsSrv.ListendAndServeTLS() failed with %s", err)
}
}()
}
httpSrv := makeHTTPServer()
httpSrv.Addr = ":80"
err := httpSrv.ListenAndServe()
if err != nil {
log.Fatalf("httpSrv.ListenAndServe() failed with %s", err)
}}
HTTPS的标准端口是443;
你可以只运行HTTP、只运行HTTPS或两者都运行;
如果服务器没有证书,那么它将会使用HTTP API向Let’s Encrypt服务器请求证书。
func makeServerFromMux(mux *http.ServeMux) *http.Server {
// set timeouts so that a slow or malicious client doesn't
// hold resources forever
return &http.Server{
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 120 * time.Second,
Handler: mux,
}
}
func makeHTTPToHTTPSRedirectServer() *http.Server {
handleRedirect := func(w http.ResponseWriter, r *http.Request) {
newURI := "https://" + r.Host + r.URL.String()
http.Redirect(w, r, newURI, http.StatusFound)
}
mux := &http.ServeMux{}
mux.HandleFunc("/", handleRedirect)
return makeServerFromMux(mux)
}
func main() {
httpSrv := makeHTTPToHTTPSRedirectServer()
httpSrv.Addr = ":80"
fmt.Printf("Starting HTTP server on %sn", httpSrv.Addr)
err := httpSrv.ListenAndServe()
if err != nil {
log.Fatalf("httpSrv.ListenAndServe() failed with %s", err)
}
}
作者:SSLChina
来源:FreeBuf.COM
本文为 @ 21CTO 创作并授权 21CTO 发布,未经许可,请勿转载。
内容授权事宜请您联系 webmaster@21cto.com或关注 21CTO 公众号。
该文观点仅代表作者本人,21CTO 平台仅提供信息存储空间服务。