nginx

Nginx http to https redirection on localhost giving page redirection error


I have hosted a simple static site on localhost on Nginx in Ubuntu. But the redirection code is giving me error "Page isn't redirecting properly".

The redirecting code providing problem is:

return                301 https://$host$request_url;

I am referring the official docs.

My Nginx code is given below.

enter image description here

The procedure to generate error is:

a. If no redirecting code i.e. "return 301 https://$host$request_url;". Then on opening "https://localhost" works good. While http://localhost does not work.

b. I add redirect code so that http gets redirected to https. But it gives me "Page isn't redirecting properly". Here "http://localhost" does redirects to "https://localhost" but page isn't redirecting properly comes. See below image:

enter image description here

How to solve it?


Solution

  • In your Nginx code you're replying to an HTTPS request with a 301. You need another section where HTTP requests reply with the 301 redirecting to HTTPS.

    That is, a second server { ... } block which listens on port 80, and that one is the one which redirects, not the one listening on port 443.

    You basically created a loop where HTTPS requests redirect to themselves.

    Sometimes wrongly set cookies create this kind of loop which is why the browser is hinting at that.