【问题标题】:How to make nginx redirect based on the value of a header?如何根据标头的值进行 nginx 重定向?
【发布时间】:2014-12-01 03:44:06
【问题描述】:

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

为了区分两者,Cloudflare 包含一个 X-Forwarded-Proto 标头,根据用户的连接设置为“http”或“https”。

我想将带有 X-Forwarded-Proto: http 标头的每个请求重定向到我网站的 SSL 版本。如何通过 nginx 配置实现这一点?

【问题讨论】:

  • 请注意,CloudFlare 不托管您网站的内容。注意:PageRules 在这里可能也有效,因为看起来您只是在尝试将 http:// 转发到 https://。 PageRules相关信息:support.cloudflare.com/hc/en-us/articles/…

标签: nginx cloudflare


【解决方案1】:

最简单的方法是使用if 指令。如果有更好的方法,请告诉我,正如人们所说的 if 指令效率低下。 Nginx 将标头中的破折号转换为下划线,因此 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... 
}

【讨论】:

  • 不确定你和什么人交谈,但如果不是低效的。当被用于重写领域之外的目的时,它很容易出错。正确阅读 if is evil 文章以了解它的缺点。您的解决方案就是它的设计目的,所以它应该可以正常工作。
  • 只是一个小提示:如果您有多个 server_name 值,最好将返回字符串替换为更通用的版本:return 301 https://$host$request_uri;
  • 伙计,如果在 nginx 中是邪恶的;) "if" 生成实例数,因此 nginx 变慢并且需要更多内存。
  • 如果在这种情况下不是邪恶的:“如果在位置上下文中,唯一可以在内部完成的 100% 安全的事情是:返回并重写”nginx.com/resources/wiki/start/topics/depth/ifisevil
【解决方案2】:

尝试使用 map 指令:http://nginx.org/en/docs/http/ngx_http_map_module.html#map

类似的...

map $http_x_forwarded_proto     $php_backend {
    "https"          "https_php_backend named loc";
    default        "default_php_backend named loc";
}
server{
    location / {
         proxy_pass http://$php_backend;
    }
}

这段代码是抽象的,但你可以试试……

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 1970-01-01
    • 2014-02-08
    • 2016-06-22
    相关资源
    最近更新 更多