From 301 Loop to Complete Solution

When using Cloudflare as a CDN and SSL provider, many developers encounter redirect loop issues, especially when configuring www to non-www redirects and HTTP to HTTPS redirects. This comprehensive guide will walk you through the proper configuration of Cloudflare Flexible SSL mode with Nginx to achieve perfect HTTPS redirect strategies.

Problem Background

I encountered a typical issue while configuring domain redirects. The goal was to implement the following redirect logic:

  • `http://www.example.com` → `https://example.com` (301)
  • `http://example.com` → `https://example.com` (301)
  • `https://www.example.com` → `https://example.com` (301)
  • `https://example.com` → Display content normally (200)

However, when accessing https://example.com, it returned a 301 redirect instead, creating a redirect loop.

Problem Analysis

How Cloudflare Flexible SSL Mode Works

In Flexible SSL mode:

  1. User to Cloudflare: Encrypted connection (HTTPS)
  2. Cloudflare to origin server: Unencrypted connection (HTTP)

This means even when users access https://example.com, the request reaching your Nginx server is still HTTP (port 80).

Initial Incorrect Configuration

if ($server_port = 80) {
  rewrite ^(.*)$ https://example.com$uri permanent;
}
if ($host ~* ^www\.example\.com$){
  rewrite ^(.*)$ https://example.com$uri permanent;  
}

This configuration has issues:

  • When users access `https://example.com`
  • Cloudflare forwards as HTTP to Nginx (port 80)
  • The first if condition triggers, causing a 301 redirect
  • Creates a redirect loop

Perfect Solution

1. Cloudflare Settings

Configure the following settings in your Cloudflare dashboard:

SSL/TLS Settings:

  • SSL/TLS encryption mode: **Flexible**
  • Always Use HTTPS: **Enabled**
  • Automatic HTTPS Rewrites: **Enabled**

2. Key Features Explanation

Always Use HTTPS

  • Uses 301 redirects to redirect all HTTP requests to HTTPS
  • Works at the user-to-Cloudflare level
  • Does not conflict with Flexible SSL

Automatic HTTPS Rewrites

  • Automatically rewrites HTTP links in page content to HTTPS
  • Solves mixed content warning issues
  • Improves website security and SEO performance

3. Nginx Configuration

Use separate server blocks for clearer logic:

# Handle www subdomain redirects
server {
    listen 80;
    server_name www.example.com;
    
    # www domain always redirects to https://example.com
    return 301 https://example.com$request_uri;
}

# Handle main domain server {     listen 80;     server_name example.com;          # Normal content handling     # HTTP->HTTPS redirects handled by Cloudflare's Always Use HTTPS     root /var/www/example.com;     index index.html index.php;          location / {         try_files $uri $uri/ =404;     }          # If using PHP     location ~ \.php$ {         fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;         fastcgi_index index.php;         fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;         include fastcgi_params;     } } `

Complete Request Flow

1. http://www.example.com

User request → Cloudflare Always Use HTTPS → https://www.example.com  
→ Cloudflare forwards HTTP to Nginx → Nginx redirects to https://example.com
→ Final: https://example.com (200)

2. http://example.com

User request → Cloudflare Always Use HTTPS → https://example.com
→ Cloudflare forwards HTTP to Nginx → Display content normally
→ Final: https://example.com (200)

3. https://www.example.com

User request → Cloudflare forwards HTTP to Nginx → Nginx redirects to https://example.com  
→ Final: https://example.com (200)

4. https://example.com

User request → Cloudflare forwards HTTP to Nginx → Display content normally
→ Final: https://example.com (200)

Deployment Steps

1. Update Cloudflare Settings

  1. Log into Cloudflare dashboard
  2. Go to SSL/TLS → Overview, ensure mode is **Flexible**
  3. Go to SSL/TLS → Edge Certificates
  4. Enable **Always Use HTTPS**
  5. Enable **Automatic HTTPS Rewrites**

2. Update Nginx Configuration

# Edit configuration file
sudo nano /etc/nginx/sites-available/example.com

# Check configuration syntax sudo nginx -t

# Reload configuration sudo nginx -s reload `

3. Clear Cache

Clear cache in Cloudflare dashboard to ensure new configuration takes effect immediately.

Testing and Verification

Use curl commands to test various scenarios:

# Test HTTP redirects
curl -I http://example.com
curl -I http://www.example.com

# Test HTTPS redirects curl -I https://www.example.com

# Test final target curl -I https://example.com `

Expected results:

  • First three commands should return `301 Moved Permanently`
  • Last command should return `200 OK`

Solution Advantages

1. Performance Optimization

  • Cloudflare edge nodes handle most redirects
  • Reduces origin server load
  • Global acceleration and caching

2. Security

  • Complete HTTPS encryption (user-facing)
  • Automatic mixed content handling
  • Protection against man-in-the-middle attacks

3. Cost-Effectiveness

  • Uses Cloudflare's free SSL certificates
  • No need to purchase and maintain SSL certificates
  • Simplified server configuration

4. SEO-Friendly

  • Unified HTTPS URL structure
  • Avoids duplicate content issues
  • Improves search engine rankings

Frequently Asked Questions

Q: Do Always Use HTTPS and SSL Flexible conflict?

A: They don't conflict at all. Always Use HTTPS works at the user-to-Cloudflare level, while SSL Flexible works at the Cloudflare-to-origin-server level. They operate at different layers.

Q: Why not configure SSL directly on the server?

A: Flexible mode is suitable for scenarios where:

  • Simple server configuration without SSL certificate management
  • Leveraging Cloudflare's global edge nodes for performance optimization
  • Getting high-quality SSL certificates and security services for free

Q: How to confirm the configuration is working?

A: You can verify through:

  • Browser developer tools to check network requests
  • Online SSL testing tools
  • curl command line testing of various URLs

Advanced Configuration Options

Alternative Single Server Block Approach

server {
    listen 80;
    server_name example.com www.example.com;
    
    # Handle www redirects first
    if ($host = www.example.com) {
        return 301 https://example.com$request_uri;
    }
    
    # Normal content handling for non-www
    root /var/www/example.com;
    index index.html index.php;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

Detecting Cloudflare Headers (Advanced)

For more sophisticated setups, you can detect Cloudflare-specific headers:

# Only redirect real HTTP requests, not Cloudflare's backend requests
if ($http_cf_visitor !~ '{"scheme":"https"}') {
    return 301 https://example.com$request_uri;
}

Monitoring and Troubleshooting

Log Analysis

Monitor your Nginx logs to ensure proper redirect behavior:

# Watch access logs
sudo tail -f /var/log/nginx/access.log

# Check error logs sudo tail -f /var/log/nginx/error.log `

Common Issues and Solutions

  1. **Redirect loops**: Check for conflicting redirect rules in both Cloudflare and Nginx
  2. **Mixed content warnings**: Ensure Automatic HTTPS Rewrites is enabled
  3. **SSL certificate errors**: Verify Cloudflare SSL mode is correctly set to Flexible

Best Practices

1. Configuration Management

  • Keep separate server blocks for different domains/subdomains
  • Use version control for Nginx configurations
  • Document any custom modifications

2. Security Considerations

  • Regularly update Cloudflare security settings
  • Monitor SSL certificate status
  • Enable additional Cloudflare security features as needed

3. Performance Optimization

  • Configure appropriate caching rules
  • Enable Cloudflare compression
  • Use Cloudflare's image optimization features

Conclusion

By properly configuring Cloudflare's Always Use HTTPS and Automatic HTTPS Rewrites, combined with clean Nginx redirect rules, we achieve:

  1. **Perfect user experience**: All access ultimately points to `https://example.com`
  2. **Clean server configuration**: Nginx only needs to handle www redirects
  3. **High performance and security**: Full utilization of Cloudflare's edge network advantages
  4. **Cost-effective solution**: Enterprise-grade SSL services for free

This configuration not only solves redirect loop issues but also provides a scalable, high-performance HTTPS deployment strategy suitable for most web application scenarios. The separation of concerns between Cloudflare (handling SSL termination and HTTP→HTTPS redirects) and Nginx (handling subdomain redirects and content serving) creates a robust and maintainable architecture.

Whether you're running a simple static site or a complex web application, this approach provides the foundation for secure, fast, and SEO-friendly HTTPS implementation.