ssl - 使用 SSL 在 Nginx 反向代理后面运行 Go 服务器

标签 ssl go nginx

我在互联网上进行了一些挖掘,但没有找到任何类似的东西(至少接近任何对我有用的解决方案)。

本质上,我在 127.0.0.1:1337 上本地运行 Golang 服务器,我希望它可以在全局范围内访问,因此我使用 Nginx 转发来自 https://api 的流量。 example.com/ 到我的 API 来检索信息。

话虽如此,我只是将我的 Golang 服务器设置为在端口 1337 上监听和提供服务,并且我的 Nginx 配置设置为重定向所有 HTTP 流量(对于所有域)到 HTTPS:

server {
    listen 80 default_server;

    server_name _; 
    return 301 https://$host$request_uri;
}

然后我将流量重定向到端口 1337:

server {
    server_name api.example.com;
    location / {
        proxy_pass http://127.0.0.1:1337;
    }

    listen 443 ssl;
    ssl_certificate_key /etc/nginx/ssl/private.key;
    ssl_certificate /etc/nginx/ssl/cert.crt;   
}

问题在于,我发现自己不断收到从 HTTPS 到 HTTP 的重定向(按照 wget),最终收到 Too Many Redirects 错误。

如果有人可以提供一些指导,我将非常感激!

最佳答案

server_name _; 匹配找不到匹配项的服务器名称。

我以前也这么做过。

查看我的 nginx 配置来代理 api 后端:

# ssl
ssl_certificate      /etc/nginx/cert/live/ybilly.com/fullchain.pem;
ssl_certificate_key  /etc/nginx/cert/live/ybilly.com/privkey.pem;

# http to https
server {
  listen 80 default_server;
  listen [::]:80 default_server;
  server_name ybilly.com www.ybilly.com *.ybilly.com;
  return 301 https://$host$request_uri;
}

# api backend
server {
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  server_name *.ybilly.com;

  location / {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
    proxy_set_header Host $host;
    proxy_set_header X-Real-Ip $remote_addr;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_pass_header Set-Cookie;
    proxy_read_timeout                 900;
    proxy_buffers 32 4k;
    proxy_pass http://127.0.0.1:8080/;
  }

}

关于ssl - 使用 SSL 在 Nginx 反向代理后面运行 Go 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54273638/

相关文章:

asp.net - WCF 同步与异步

go - golang中参数中的动态结构

string - Go 中别名类型之间的转换会创建副本吗?

python - Flask Gunicorn 应用无法让 __name__ 等于 '__main__'

ssl - 在没有 “www”的情况下访问时将证书添加到我的站点

node.js - 我应该在生产中使用 Nginx 来服务 React 吗?

所有域的 SSL 证书

php - 无法在 xampp 中启动 apache

ssl - 如果我的参数已经加密,我应该使用 SSL 吗?

caching - Go中的线程安全(Goroutine-safe)缓存