Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Host Multiple Golang Sites on One IP and Serve Depending on Domain Request?

Tags:

http

port

nginx

go

I'm running a VPS with Ubuntu installed. How can I use the same VPS (same IP) to serve multiple Golang websites without specifying the port (xxx.xxx.xxx.xxx:8084) in the url?

For example, Golang app 1 is listening on port 8084 and Golang app 2 is listening on port 8060. I want Golang app 1 to be served when someone requests from domain example1.com and Golang app 2 to be served when someone requests from domain example2.com.

I'm sure you can do this with Nginx but I haven't been able to figure out how.

like image 369
Ari Seyhun Avatar asked Oct 06 '16 10:10

Ari Seyhun


People also ask

Can you host multiple websites from the same IP?

Name-based virtual hosting is the most commonly used method to host multiple websites on the same IP address and Port.

Can I host multiple domains on one server?

Absolutely. With the right type of hosting account, you can host as many websites as your particular hosting package will allow. Be sure to check with your hosting provider before you begin hosting more than one domain.


2 Answers

Nginx free solution.

First of all you can redirect 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

Then use gorilla/mux or similar to create a route for every host and even get a "subrouter" from it

r := mux.NewRouter()
s := r.Host("www.example.com").Subrouter()

So the complete solution would be

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)
}
like image 73
Marsel Novy Avatar answered Nov 15 '22 06:11

Marsel Novy


Please, try out the following code,

server {
   ...
   server_name www.example1.com example1.com;
   ...
   location / {
      proxy_pass app_ip:8084;
   }
   ...
}

...

server {
   ...
   server_name www.example2.com example2.com;
   ...
   location / {
      proxy_pass app_ip:8060;
   }
   ...
}

app_ip is the ip of the machine wherever same is hosted, if on the same machine, put http://127.0.0.1 or http://localhost

like image 38
Satys Avatar answered Nov 15 '22 06:11

Satys