Docker nginx将HTTP重定向到HTTPS

问题描述:

我正在使用Docker设置服务器。一个容器运行SSL配置的nginx映像。第二个容器运行一个简单的节点应用程序(在端口3001上)。我有两个容器与--link docker参数进行通信。Docker nginx将HTTP重定向到HTTPS

我需要将所有HTTP请求重定向到HTTPS。看着其他线程和在线资源,我发现了return 301 https://$host$request_uri。当我在浏览器中输入http://localhost时,我在浏览器中获取上游的名称(https://node_app而不是https://localhost)。如何在不定义server_name或明确定义域的情况下成功重定向?

编辑:我应该澄清,直接在浏览器中访问https://localhost的作品。 HTTP不。

这是我的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; 
    } 

    } 

} 
+0

就像你运行Nginx的裸机Linux机器做同样的方式。只需谷歌一分钟或更少。在Docker中公开两个监听端口似乎并不是你的问题(HTTPS被暴露的方式与HTTP相同,以防万一) – agg3l

+0

'nginx'配置看起来很好。节点应用程序可以更改域名吗?使用浏览器插件或curl分析HTTP响应中的“位置”标头,以确定确切的重定向顺序。 –

+0

@RichardSmith Ran'curl http:// localhost - head'并得到以下回应。看起来位置正确。 'HTTP/1.1 301永久移动 服务器:nginx/1.11.5 日期:太阳,2016年10月16日13时58分39秒GMT 的Content-Type:text/html的 的Content-Length:185 连接:备存─ alive 位置:https:// localhost /' – Shiv

看起来一切正常。尝试了一些curl调用,以确保标题设置正确(信贷给@RichardSmith推荐)。也在不同的浏览器中测试过。一切正常!原来我需要清除主浏览器的缓存。不知道为什么,但它解决了这个问题!

有兴趣的人控制的301高速缓存重定向nginx的完成:https://serverfault.com/questions/394040/cache-control-for-permanent-301-redirects-nginx