我正在运行一个安装了 Ubuntu 的 VPS。如何在不指定端口(xxx.xxx.xxx.xxx:8084)的情况下使用同一个VPS(同一个IP)服务多个Golang网站?
例如,Golang 应用程序 1 正在监听端口 8084,Golang 应用程序 2 正在监听端口 8060。我希望当有人从域 example1.com
请求时提供 Golang 应用程序 1,当有人从域 example2.com
请求时提供 Golang 应用程序 2。
我相信你可以用 Nginx 做到这一点,但我一直无法弄清楚如何。
最佳答案
Nginx 免费解决方案。
首先你可以重定向connections on port 80 as a normal user
sudo apt-get install iptables-persistent
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8000
sudo netfilter-persistent save
sudo netfilter-persistent reload
然后使用gorilla/mux或类似地为每个主机创建一个路由,甚至从中获得一个“子路由器”
r := mux.NewRouter()
s := r.Host("www.example.com").Subrouter()
所以完整的解决方案是
package main
import (
"net/http"
"github.com/gorilla/mux"
"fmt"
)
func Example1IndexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello www.example1.com!") // send data to client side
}
func Example2IndexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello www.example2.com!") // send data to client side
}
func main() {
r := mux.NewRouter()
s1 := r.Host("www.example1.com").Subrouter()
s2 := r.Host("www.example2.com").Subrouter()
s1.HandleFunc("/", Example1IndexHandler)
s2.HandleFunc("/", Example2IndexHandler)
http.ListenAndServe(":8000", nil)
}
关于http - 在一个 IP 上托管多个 Golang 站点并根据域请求提供服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39894171/