2
votes

I'm setting up a server using Docker. One container runs an nginx image with SSL configured. A second container runs with a simple node app (on port 3001). I've got the two containers communicating with a --link docker parameter.

I need to redirect all HTTP requests to HTTPS. Looking at other threads and online sources, I found 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). How can I successfully redirect without defining a server_name or explicitly defining a domain?

Edit: I should clarify that accessing https://localhost directly in the browser works. HTTP does not.

Here's my nginx.conf file:

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;
    }

  }

}
1
just the same way as you do for bare-metal linux box running nginx. Just google it for a minute or less. Exposing both listen ports within docker doesn't seem to be your problem at the moment (HTTPS to be exposed same way as HTTP, just in case) - agg3l
The nginx configuration looks fine. Could the node app be changing the domain name? Use a browser plug-in or curl to analyse the Location header in the HTTP response to identify the exact sequence of redirects. - Richard Smith
@RichardSmith Ran curl http://localhost --head and got the following response. Looks like the location is correct. HTTP/1.1 301 Moved Permanently Server: nginx/1.11.5 Date: Sun, 16 Oct 2016 13:58:39 GMT Content-Type: text/html Content-Length: 185 Connection: keep-alive Location: https://localhost/ - Shiv
What happens if you change proxy_pass to proxy_pass http://node_app;? - Richard Smith
This is very weird! I'm only seeing this behavior in Google Chrome. Safari and Firefox are able to successfully redirect http://localhost to https://localhost. Any ideas? - Shiv

1 Answers

2
votes

Looks like everything was okay. Tried some curl calls to make sure headers were being set correctly (credits to @RichardSmith for recommendation). 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