#Cloudflare Flexible SSL + Nginx Perfect HTTPS Redirect: 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:
- User to Cloudflare: Encrypted connection (HTTPS)
- 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
1if ($server_port = 80) {
2 rewrite ^(.*)$ https://example.com$uri permanent;
3}
4if ($host ~* ^www\.example\.com$){
5 rewrite ^(.*)$ https://example.com$uri permanent;
6}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:
1# Handle www subdomain redirects
2server {
3 listen 80;
4 server_name www.example.com;
5
6 # www domain always redirects to https://example.com
7 return 301 https://example.com$request_uri;
8}
9
10# Handle main domain
11server {
12 listen 80;
13 server_name example.com;
14
15 # Normal content handling
16 # HTTP->HTTPS redirects handled by Cloudflare's Always Use HTTPS
17 root /var/www/example.com;
18 index index.html index.php;
19
20 location / {
21 try_files $uri $uri/ =404;
22 }
23
24 # If using PHP
25 location ~ \.php$ {
26 fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
27 fastcgi_index index.php;
28 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
29 include fastcgi_params;
30 }
31}#Complete Request Flow
#1. http://www.example.com
1User request → Cloudflare Always Use HTTPS → https://www.example.com
2→ Cloudflare forwards HTTP to Nginx → Nginx redirects to https://example.com
3→ Final: https://example.com (200)#2. http://example.com
1User request → Cloudflare Always Use HTTPS → https://example.com
2→ Cloudflare forwards HTTP to Nginx → Display content normally
3→ Final: https://example.com (200)#3. https://www.example.com
1User request → Cloudflare forwards HTTP to Nginx → Nginx redirects to https://example.com
2→ Final: https://example.com (200)#4. https://example.com
1User request → Cloudflare forwards HTTP to Nginx → Display content normally
2→ Final: https://example.com (200)#Deployment Steps
#1. Update Cloudflare Settings
- Log into Cloudflare dashboard
- Go to SSL/TLS → Overview, ensure mode is Flexible
- Go to SSL/TLS → Edge Certificates
- Enable Always Use HTTPS
- Enable Automatic HTTPS Rewrites
#2. Update Nginx Configuration
1# Edit configuration file
2sudo nano /etc/nginx/sites-available/example.com
3
4# Check configuration syntax
5sudo nginx -t
6
7# Reload configuration
8sudo 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:
1# Test HTTP redirects
2curl -I http://example.com
3curl -I http://www.example.com
4
5# Test HTTPS redirects
6curl -I https://www.example.com
7
8# Test final target
9curl -I https://example.comExpected 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
1server {
2 listen 80;
3 server_name example.com www.example.com;
4
5 # Handle www redirects first
6 if ($host = www.example.com) {
7 return 301 https://example.com$request_uri;
8 }
9
10 # Normal content handling for non-www
11 root /var/www/example.com;
12 index index.html index.php;
13
14 location / {
15 try_files $uri $uri/ =404;
16 }
17}#Detecting Cloudflare Headers (Advanced)
For more sophisticated setups, you can detect Cloudflare-specific headers:
1# Only redirect real HTTP requests, not Cloudflare's backend requests
2if ($http_cf_visitor !~ '{"scheme":"https"}') {
3 return 301 https://example.com$request_uri;
4}#Monitoring and Troubleshooting
#Log Analysis
Monitor your Nginx logs to ensure proper redirect behavior:
1# Watch access logs
2sudo tail -f /var/log/nginx/access.log
3
4# Check error logs
5sudo tail -f /var/log/nginx/error.log#Common Issues and Solutions
- Redirect loops: Check for conflicting redirect rules in both Cloudflare and Nginx
- Mixed content warnings: Ensure Automatic HTTPS Rewrites is enabled
- 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:
- Perfect user experience: All access ultimately points to
https://example.com - Clean server configuration: Nginx only needs to handle www redirects
- High performance and security: Full utilization of Cloudflare's edge network advantages
- 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.