我在 Cloudflare 代理后面托管一个网站,这意味着对我的服务器的所有请求都通过端口 80,即使 Cloudflare 处理 HTTP(端口 80)和 HTTPS(端口 443)流量。
为了区分两者,Cloudflare 包含一个 X-Forwarded-Proto
header 根据用户的连接设置为“http”或“https”。
我想用 X-Forwarded-Proto: http
重定向每个请求 header 到我网站的 SSL 版本。如何使用 nginx 配置来实现这一点?
最佳答案
最简单的方法是使用 if
指示。如果有更好的方法,请告诉我,正如人们所说的if
指令效率低下。 Nginx 将 header 中的破折号转换为下划线,因此 X-Forwarded-Proto
变成 $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 - 如何根据 header 的值进行 nginx 重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26223733/