301 redirect issue with load balancer

I recently created a lightsail NGINX instance on AWS.

I opened my server block file and added the below code:

server {
  listen 80;
  server_name www.example.com
  return 301 https://example.com
}

When I run

curl -I example.com

It returns the correct response saying it is redirecting to the non www url.

My instance DNS resolves to a vp6 address because I have load balancers enabled. The load balancers automatically redirect from http to https.

I have an A record which point to the server ip.
Also, tried an a record which points to the load balancers.

With either record it says failed to load to many redirects.

Any idea what could be causing this?

When I try to access the original config file created by AWS for the load balancers, there are just tons of @@@@@@ in the file. So all my server blocks are in another file.

Any insights greatly appreciated.

1 Like

The block you’ve posted is fine, so the problem is in some the configuration you have not posted. Which makes it impossible to see where the issue lies.

Could you post the other configurations as well please?

1 Like

This is the only other thing in the file:

server {
    # Port to listen on, can also be set in IP:PORT format
    listen  443 ssl;

    ssl_certificate      bitnami/certs/server.crt;
    ssl_certificate_key  bitnami/certs/server.key;

    include  "/opt/bitnami/nginx/conf/bitnami/*.conf";

    location /status {
        stub_status on;
        access_log   off;
        allow 127.0.0.1;
        deny all;
    }
}

When I add this to the same file, underneath the above server block., the server doesn’t pass health check.

server {
  listen 80;
  listen 443 SSL;
  server_name www.example.com;
  return 301 https://example.com;
}

The above snippet works but then the server shuts down and says doesn’t pass health check.

That’s probably because you told it to listen to port 443 with SSL but didn’t pass it the SSL certificates.

You could try this:

server {
  listen 80;
  listen 443 SSL;

  ssl_certificate      bitnami/certs/server.crt;
  ssl_certificate_key  bitnami/certs/server.key;

  server_name www.example.com;

  return 301 https://example.com;
}

I tried the suggestion and every other possible alternative.

It works initially but then the server says health check failed, and in the browser, while it redirects to the correct URL, it then says too many redirects which then disables the server and the second server takes over.

I have a feeling that there is some file that I can’t find which has already defined a redirect rule so when I apply the redirect rule in the server config file above, it then just says too many redirects. I’ve searched the net to where the location is but the only doc articles that can be found are for Apache.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.