Nginx 反向代理配置及测试
2021-11-01 10:00:00
本文关心以下内容
配置上下文
- HTTP Context: http, server
- TCP Context: stream, server
经过反向代理获取请求的HOST和客户端IP
- HTTP & WS
proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr;
- TCP 可考虑参考这些(要求不高则客户端携带IP)
配置示例
- WS
map $http_upgrade $connection_upgrade { default upgrade; '' close; } server { listen 8080; location /echo { proxy_pass http://172.20.10.5:8080; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; } }
- HTTP
server { listen 8088; location / { proxy_pass http://172.20.10.5:8088; } }
- TCP
server { listen 8888; proxy_pass 172.20.10.5:8888; }
测试
- HTTP & TCP 搭配 curl & telnet 进行测试
func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { whoami := fmt.Sprintf("http from %s\n", r.RemoteAddr) fmt.Fprint(w, whoami) log.Print(whoami) }) go http.ListenAndServe(":8088", nil) l, err := net.Listen("tcp", ":8888") if err != nil { log.Fatal(err) } defer l.Close() for { conn, err := l.Accept() if err != nil { log.Fatal(err) } go func(c net.Conn) { whoami := fmt.Sprintf("tcp from %s\n", c.RemoteAddr()) io.WriteString(c, whoami) log.Print(whoami) io.Copy(c, c) c.Close() }(conn) } }
- WebSocket 可借助 echo 测试