2

I want to redirect localhost request to HTTPS. This is what my .conf looks like:

server {
  listen 80;
  listen 443 ssl;

  ssl_certificate /etc/ssl/localhost.crt;
  ssl_certificate_key /etc/ssl/localhost.key;

  server_name localhost;

  return 301 https://$server_name$request_uri;

  location / {
    root /usr/share/nginx/html;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
  }
}

I run this in a Docker container with -p 80:80 -p 443:443 but calling the server from the browser results in a loop of https://localhost/ calls.

Phil
  • 123
  • 1
  • 5

1 Answers1

4

Both your https and http servers share the same configuration block, which tells nginx to redirect to https://$server_name$request_uri address. That is the reason for the redirect loop.

You need to have a separate server block for https, where you serve the actual content, and you only have the redirect in the http block.

In your case the configuration would look something like this:

server {
    listen 80;

    server_name localhost;

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

server {
    listen 443 ssl;

    ssl_certificate /etc/ssl/localhost.crt;
    ssl_certificate_key /etc/ssl/localhost.key;

    server_name localhost;

    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
        try_files $uri $uri/ /index.html =404;
    }
}
Tero Kilkanen
  • 36,796
  • 3
  • 41
  • 63