dongqiao1964
dongqiao1964
2014-07-26 03:15

转到Webapp和Nginx:关于监听,fastcgi和反向代理的困惑

已采纳

So I'm trying to create a webapp on Go that accepts all requests from one domain only, with a unique IP, and have all other domains and IPs handled by Nginx (and served with PHP).

I'm confused about how this is done, it looks like many people are doing this by configuring Nginx to pass requests from a certain domain to FastCGI, which is then listened to from the Go webapp. Something like this:

Nginx.conf

server_name www.mydomain.com;
listen 123.123.123.123;
include         fastcgi.conf;
fastcgi_pass    127.0.0.1:9001;

Go

func main() {
 listener, _ := net.Listen("tcp", "127.0.0.1:9001")
 srv := new(MyServerObject)
 fcgi.Serve(listener, srv)
}

What I don't understand is this: here we have Nginx listening for a particular domain on a particular IP and then passing that to fastcgi, which then passes it to Go.

Why do this? Can I not just have Nginx not listen for this domain, and then Go listen for this domain only? Then the same would be achieved more efficiently and without the reverse proxy.

Since I can use a dedicated IP for the domain that Go is listening to, then there would (in my thinking) be no conflict. Nginx would simply not be listening to 123.123.123.123:80 and Go would be listening to 123.123.123.123:80... hence no need for the reverse proxy and fastcgi.

Is my thinking on this correct, or am I missing something?

If it is correct, is all I have to do remove the listener for this IP/domain from Nginx and then use Go code like the below?

func main() {
 http.HandleFunc("/", someFunction)
 http.ListenAndServe("123.123.123.123:80", nil)
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doufei9946 doufei9946 7年前

    Yes you can have Go listen directly on that IP and it will work fine, there are other uses for nginx, like caching and serving static files.

    Also you could have go listen on http.ListenAndServe("127.0.0.1:9020", nil) and proxy from nginx to it:

    server {
            listen 123.123.123.123:80;
            location  /  {
                    proxy_set_header        X-Real-IP $remote_addr;
                    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
                    proxy_pass http://127.0.0.1:9020/;
            }
    }
    

    It takes few minutes of testing.

    So ask yourself this, do you need nginx to cache some files or serve static files for you? if yes, use it in front of go, if not, use go directly.

    Also if you were to use nginx, the proxy method is probably faster than fcgi.

    点赞 评论 复制链接分享