简体   繁体   English

Docker nginx 将 HTTP 重定向到 HTTPS

[英]Docker nginx redirect HTTP to HTTPS

I'm setting up a server using Docker.我正在使用 Docker 设置服务器。 One container runs an nginx image with SSL configured.一个容器运行一个配置了 SSL 的 nginx 镜像。 A second container runs with a simple node app (on port 3001).第二个容器运行一个简单的节点应用程序(在端口 3001 上)。 I've got the two containers communicating with a --link docker parameter.我有两个容器与 --link docker 参数进行通信。

I need to redirect all HTTP requests to HTTPS.我需要将所有 HTTP 请求重定向到 HTTPS。 Looking at other threads and online sources, I found return 301 https://$host$request_uri .查看其他线程和在线资源,我发现return 301 https://$host$request_uri When I type http://localhost in the browser I'm getting the upstream's name in the browser ( https://node_app instead of https://localhost ).当我在浏览器中输入http://localhost时,我会在浏览器中获取上游的名称( https://node_app而不是https://localhost )。 How can I successfully redirect without defining a server_name or explicitly defining a domain?如何在不定义 server_name 或明确定义域的情况下成功重定向?

Edit : I should clarify that accessing https://localhost directly in the browser works.编辑:我应该澄清直接在浏览器中访问https://localhost有效。 HTTP does not. HTTP 没有。

Here's my nginx.conf file:这是我的 nginx.conf 文件:

worker_processes 1;

events { worker_connections 1024; }

http {

  upstream node_app {
    server node:3001;
  }

  server {
    listen 80;
    return 301 https://$host$request_uri;
  }

  server {
    listen 443 ssl;

    ssl_certificate /etc/nginx/ssl/server.crt;
    ssl_certificate_key /etc/nginx/ssl/server.key;

    location / {
      proxy_pass http://node_app/;
      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection 'upgrade';
      proxy_set_header Host $host;
      proxy_cache_bypass $http_upgrade;
    }

  }

}

Looks like everything was okay.看起来一切正常。 Tried some curl calls to make sure headers were being set correctly (credits to @RichardSmith for recommendation).尝试了一些 curl 调用以确保标题设置正确(归功于@RichardSmith 的推荐)。 Also tested in different browsers.也在不同的浏览器中进行了测试。 Everything worked!一切正常! Turns out I needed to clear my primary browser's cache.原来我需要清除我的主浏览器的缓存。 Not sure why, but it resolved the issue!不知道为什么,但它解决了问题!

For anyone interested in controlling the cache of 301 redirects done by nginx: https://serverfault.com/questions/394040/cache-control-for-permanent-301-redirects-nginx对于任何有兴趣控制由 nginx 完成的 301 重定向缓存的人: https : //serverfault.com/questions/394040/cache-control-for-permanent-301-redirects-nginx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM