MENU

nginx+goproxy反代

September 8, 2019 • linux相关

需求

goproxy-server 运行的本地 web 服务 127.0.0.1:8080nginx 反向代理到 80/443 端口。
因为服务器上 80/443 端口已经被 nginx 使用了,所以当使用 goproxy-server 提供 web 服务时只能跑在非 80/443 端口上(以 8080 端口为例)。

nginx 配置

vhost 配置内容如下:

map $scheme $go_proxy_port {
    "http" "8080";
    "https" "8080";
    default "8080";
}
server
    {
        listen 443 ssl http2;
        server_name example.com www.example.com;

        ssl on;
        ssl_certificate /home/myssl/example.com/site.pem;
        ssl_certificate_key /home/myssl/example.com/site.key;
        ssl_session_timeout 5m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers "EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5";
        ssl_session_cache builtin:1000 shared:SSL:10m;
        # openssl dhparam -out /usr/local/nginx/conf/ssl/dhparam.pem 2048
        ssl_dhparam /usr/local/nginx/conf/ssl/dhparam.pem;

        location / {
            proxy_pass              $scheme://127.0.0.1:$go_proxy_port;
            proxy_redirect          ~^$scheme://127.0.0.1:$go_proxy_port(.*)    $scheme://$server_name$1;
            proxy_set_header        Host             $http_host;
            proxy_set_header        X-Real-IP        $host;
            proxy_set_header        X-Forwarded-For  $proxy_add_x_forwarded_for;
        }
    }
server
    {
        listen 80;
        server_name example.com www.example.com;
        return 301 https://$server_name$request_uri;
    }

说明

  1. 强制 http2https;
  2. https 部署 ssl 证书;
  3. 反代本机 127.0.0.1:8080;
  4. 后端可以只部署 httphttps 其中一种,当然也可以两者共存,估计得分成两套端口转发,未测。
  5. 本文基于 军哥 lnmp 环境 nginx 反向代理配置
  6. goproxy 官方手册
Last Modified: September 22, 2019