Andy Jarrett // Code. Develop. Create.

NGINX redirect loops with SSL and CloudFlare

Clouds
Photo by CHUTTERSNAP on Unsplash
I've been having trouble with my andyjarrett.com domain (though not my .co.uk one?) and redirection issues. Sometimes it would affect the browser, sometimes it wouldn't. Well last night was the last time its happening. So this is there I was
curl https://www.andyjarrett.com
<html>
<head><title>307 Temporary Redirect</title></head>
<body>
<center><h1>307 Temporary Redirect</h1></center>
<hr><center>nginx/1.18.0 (Ubuntu)</center>
</body>
</html> 

When I dived deeper in to it with curl -L https://www.andyjarrett.com I got this

curl: (47) Maximum (50) redirects followed

Didn't really help, so next on to the logs sudo tail -f /var/log/nginx/error.log which didn't tell me much but did highlight headers like CF-RAY, CF-Visitor, and CDN-Loop. Now I'm thinking Cloudflare might be the cause of the redirection loop, especially if there's a mismatch between how Cloudflare is configured to handle SSL and how my server is handling it. Finally I got to CloudFlare > Domain (andyjarrett.com) > SSL/TLS > Overview and "SSL/TLS encryption".

Solution: Ensure that Cloudflare is set to "Full" or "Full (Strict)" mode for SSL.

Why? Mine was originall set as "Flexible," causing Cloudflare to make a HTTP requests to my server and causing the loop. From what I've learnt

  1. My Nginx server is configured to redirect all HTTP requests to HTTPS (i.e., redirect port 80 traffic to port 443).
  2. When Cloudflare operates in Flexible mode, it connects to my server via HTTP (port 80), because it assumes the server doesn't support HTTPS.
  3. When my server sees this incoming HTTP request, it triggers the redirection to HTTPS.
  4. Cloudflare receives the redirect response and tries to establish an HTTPS connection with my server again, but still over HTTP due to "Flexible" mode.
  5. This creates a loop: Cloudflare keeps making HTTP requests to my server, and my server keeps redirecting them to HTTPS.

I’m here, learning and working away. If you liked this content and want to keep me going, consider buying me a coffee. Your support keeps this site running and the coffee brewing! ☕️