大网数据广告活动
服务器运维问答

Redirect loop using cloudflare's Flexible ssl

· 52CE 我爱测

I am trying to implement Flexible SSL provided by CloudFlare to my site. Here is my nginx config: # PHP-FPM upstream; change it accordingly to your local config! upstream php-fpm { server 127.0.0.1:9000; } server { listen 80; ser…

问题原文

原帖链接 · Deqq · CC BY-SA 3.0

I am trying to implement Flexible SSL provided by CloudFlare to my site.

Here is my nginx config:

# PHP-FPM upstream; change it accordingly to your local config!
upstream php-fpm {
    server 127.0.0.1:9000;
}

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

server {
    ## Listen ports
    listen 443;

    # use _ if you want to accept everything, or replace _ with domain
    server_name example.com www.example.com;

    location / {
      #proxy_set_header        X-Forwarded-Proto $scheme;
      proxy_set_header X_FORWARDED_PROTO https;
      proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header  Host $http_host;
      proxy_set_header  X-Url-Scheme $scheme;
      proxy_redirect    off;
      proxy_max_temp_file_size 0;
    }

(...rest of config...)

However, when I try to connect to the website (Wordpress), I get a redirect loop (chrome: ERR_TOO_MANY_REDIRECTS). How do I configure nginx to prevent this?

社区高分解答

原帖链接 · AD7six · CC BY-SA 3.0

Cloudflare's flexible ssl means the connection between cloudflare and your server is always over http:

Given this - the only server block in the question of relevance is this one:

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

It should be obvious why that results in a redirect loop, there are 2 solutions to force https connections using their flexible ssl solution.

Use Cloudflare's page rules

If access to the server is exclusively via cloudflare you can use cloudflare's own page rules to modify responses for a domain, subdomain, or any url pattern:

One of the options is to force https:

Test $http_x_forwarded_proto

There are times you may want to avoid using page rules (should be rare or transitional only), for these scenarios it's possible to test the forwarded protocol and redirect based on that:

server {
   listen         80;
   server_name    example.com www.example.com;

   if ($http_x_forwarded_proto = "http") {
     return 301 https://$server_name$request_uri;
   }

   ... directives to generate a response
}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2014-12-20)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。