Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
469 views
in Technique[技术] by (71.8m points)

cloudflare - How to make nginx redirect based on the value of a header?

I'm hosting a website behind a Cloudflare proxy, which means that all requests to my server are over port 80, even though Cloudflare handles HTTP (port 80) and HTTPS (port 443) traffic.

To distinguish between the two, Cloudflare includes an X-Forwarded-Proto header which is set to "http" or "https" based on the user's connection.

I would like to redirect every request with an X-Forwarded-Proto: http header to the SSL version of my site. How can I achieve this with an nginx configuration?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The simplest way to do this is with an if directive. If there is a better way, please let me know, as people say the if directive is inefficient. Nginx converts dashes to underscores in headers, so X-Forwarded-Proto becomes $http_x_forwarded_proto.

server {
    listen 80;
    server_name example.com; # Replace this with your own hostname
    if ($http_x_forwarded_proto = "http") {
        return 301 https://example.com$request_uri;
    }

    # Rest of configuration goes here... 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...