如何用Golang实现其他域名重定向到.com主域名(如www.example.org跳转至https://example.com)

如何用Golang实现其他域名重定向到.com主域名(如www.example.org跳转至https://example.com) 我正在开发一个网络服务器,拥有多个顶级域名:.es、.uk、.asia、.it、.cc、.org

我需要将所有流量重定向,包括 www.example.comhttps://example.com

(我正在使用 Autocert 来获取 Let’s Encrypt 的 HTTPS 证书)

3 回复
  1. 在 .htaccess 文件中设置 301 重定向
  2. 将这些顶级域名托管在一个地方,并使用相同的 DNS 查询

我们两种方法都使用。

更多关于如何用Golang实现其他域名重定向到.com主域名(如www.example.org跳转至https://example.com)的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Go语言中实现这一功能的简单方法是使用某种中间件函数,检查请求的主机是否正确,否则重定向到正确的主机:

package main

import (
	"io"
	"net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {
	io.WriteString(w, "Hello world")
}

func redirectOthers(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.Host != "local.test.com" {
			http.Redirect(w, r, "http://local.test.com", 301)
			return
		}
		next.ServeHTTP(w, r)
	}
}

func main() {
	http.HandleFunc("/", redirectOthers(hello))
	http.ListenAndServe(":80", nil)
}

要测试此功能,请在您的hosts文件中添加以下行:

127.0.0.1		localhost local.test.org local.test.se local.test.com

如果您尝试访问 http://local.test.sehttp://local.test.org,将会被重定向到 http://local.test.com

在Go语言中,可以通过HTTP中间件或自定义HTTP处理程序来实现域名重定向到主域名。以下是一个完整的示例,使用net/http包和TLS配置(结合Autocert)来处理多域名重定向到https://example.com

首先,确保你已经安装了必要的包。如果使用Autocert,需要导入golang.org/x/crypto/acme/autocert

步骤1:设置域名重定向逻辑

创建一个HTTP处理程序,检查请求的主机名,如果不是目标域名(example.com),则重定向到https://example.com

package main

import (
    "fmt"
    "log"
    "net/http"
    "strings"

    "golang.org/x/crypto/acme/autocert"
)

// redirectHandler 检查主机名并重定向到主域名
func redirectHandler(targetDomain string) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        host := strings.ToLower(r.Host)
        // 检查主机名是否不是目标域名(例如,example.com)
        if host != targetDomain {
            // 构建重定向URL:使用HTTPS和目标域名,保留路径和查询参数
            redirectURL := "https://" + targetDomain + r.URL.Path
            if r.URL.RawQuery != "" {
                redirectURL += "?" + r.URL.RawQuery
            }
            http.Redirect(w, r, redirectURL, http.StatusMovedPermanently)
            return
        }
        // 如果主机名已经是目标域名,正常处理请求(例如,提供你的网站内容)
        fmt.Fprintf(w, "Welcome to %s! This is the main domain.", targetDomain)
    }
}

func main() {
    targetDomain := "example.com" // 设置你的主域名
    // 定义需要处理的域名列表,包括主域名和其他域名(用于Autocert证书)
    domains := []string{
        "example.com",
        "www.example.com",
        "example.es",
        "example.uk",
        "example.asia",
        "example.it",
        "example.cc",
        "example.org",
        // 添加其他域名...
    }

    // 设置Autocert管理器,用于自动获取Let's Encrypt证书
    certManager := &autocert.Manager{
        Prompt:     autocert.AcceptTOS,
        HostPolicy: autocert.HostWhitelist(domains...), // 只允许列表中的域名
        Cache:      autocert.DirCache("certs"),         // 证书缓存目录
    }

    // 创建HTTP服务器,使用重定向处理程序
    handler := redirectHandler(targetDomain)
    server := &http.Server{
        Addr:      ":https",
        Handler:   handler,
        TLSConfig: certManager.TLSConfig(), // 使用Autocert的TLS配置
    }

    // 启动HTTP到HTTPS的重定向服务器(在端口80)
    go func() {
        redirectServer := &http.Server{
            Addr: ":http",
            Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                // 重定向所有HTTP请求到HTTPS版本
                host := strings.ToLower(r.Host)
                redirectURL := "https://" + host + r.URL.Path
                if r.URL.RawQuery != "" {
                    redirectURL += "?" + r.URL.RawQuery
                }
                http.Redirect(w, r, redirectURL, http.StatusMovedPermanently)
            }),
        }
        log.Fatal(redirectServer.ListenAndServe())
    }()

    // 启动HTTPS服务器(在端口443)
    log.Printf("Starting HTTPS server on :https for domains: %v", domains)
    log.Fatal(server.ListenAndServeTLS("", "")) // Autocert自动处理证书文件
}

步骤2:解释代码关键部分

  • redirectHandler函数:这是一个HTTP处理程序,检查传入请求的Host头。如果主机名不是example.com(例如www.example.comexample.org),则返回301重定向到https://example.com,保留原始路径和查询参数。如果是主域名,直接响应内容(在实际应用中,你可能需要替换为你的网站处理逻辑)。
  • Autocert集成:使用autocert.Manager自动管理Let’s Encrypt证书。HostPolicy设置为允许的域名列表,确保只为这些域名获取证书。证书缓存到本地目录(例如certs/)。
  • HTTP到HTTPS重定向:在单独的goroutine中启动一个HTTP服务器(端口80),将所有HTTP请求重定向到HTTPS版本。这确保即使用户访问http://版本,也会被重定向到安全的https://

步骤3:运行和测试

  1. 将代码保存为main.go,并安装依赖:go mod init your-project && go get golang.org/x/crypto/acme/autocert
  2. 运行程序:go run main.go。服务器将在端口443(HTTPS)和端口80(HTTP重定向)监听。
  3. 测试重定向:访问http://www.example.orghttps://example.es,应自动跳转到https://example.com

注意事项

  • 确保你的域名DNS记录正确指向服务器IP。
  • 如果使用云平台,可能需要配置负载均衡器或防火墙规则允许端口80和443。
  • 在生产环境中,添加错误处理和日志记录以提高可靠性。

这个实现覆盖了你的需求:将所有域名(包括www.example.com和其他顶级域名)重定向到https://example.com,同时使用Autocert自动处理HTTPS证书。

回到顶部