问题描述
我在 Cloudflare 代理后面托管一个网站,这意味着对我的服务器的所有请求都通过端口 80,即使 Cloudflare 处理 HTTP(端口 80)和 HTTPS(端口 443)流量.
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"或https".
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 重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!