如何根据标题的值使Nginx重定向? [英] How to make nginx redirect based on the value of a header?

查看:59
本文介绍了如何根据标题的值使Nginx重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Cloudflare代理后面托管一个网站,这意味着即使Cloudflare处理HTTP(端口80)和HTTPS(端口443)流量,对服务器的所有请求都通过端口80进行。

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.

为了区分两者,Cloudflare包含了 X-Forwarded-Proto 标头,该标头设置为 http

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.

我想使用 X-Forwarded-Proto:http 标头指向我网站的SSL版本。如何使用Nginx配置实现此目标?

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?

推荐答案

最简单的方法是使用 if 指令。如果有更好的方法,请告诉我,因为人们说 if 指令效率低下。 Nginx将标头中的破折号转换为下划线,因此 X-Forwarded-Proto 变为 $ http_x_forwarded_proto

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... 
}

这篇关于如何根据标题的值使Nginx重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆