sslnginxhttps

HTTP to HTTPS Nginx too many redirects


I have a website running on a LEMP stack. I have enabled cloudflare with the website. I am using the cloudflare flexible SSL certificate for https. When i open the website in chrome it shows website redirected you too many times and in firefox has detected that the server is redirecting the request for this address in a way that will never complete. I have tried to see answers of other questions but none of them seem to solve the problem. NGINX conf file:-

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name mydomain.com www.mydomain.com;
    return 301 https://$server_name$request_uri;
}
server {
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
    root /var/www/html;

    index index.php index.html index.htm index.nginx-debian.html;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }
}

I would be highly grateful if anyone can point out what I am doing wrong.


Solution

  • Since you are using cloudflare flexible SSL your nginx config file wll look like this:-

    server {
      listen 80 default_server;
      listen [::]:80 default_server;
      server_name mydomain.com www.mydomain.com;
    
      if ($http_x_forwarded_proto = "http") {
          return 301 https://$server_name$request_uri;
      }
    
      root /var/www/html;
    
      index index.php index.html index.htm index.nginx-debian.html;
    
      location / {
         try_files $uri $uri/ =404;
      }
    
      location ~ \.php$ {
         include snippets/fastcgi-php.conf;
         fastcgi_pass unix:/run/php/php7.0-fpm.sock;
      }
    
      location ~ /\.ht {
         deny all;
      }
    }