nginx - 如何根据 header 的值进行 nginx 重定向?

标签 nginx cloudflare

我在 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/

相关文章:

nginx - 80 端口上的 heroku + nginx

ruby-on-rails - 加速 ruby​​ on rails 网站

linux - 我的 cloudflare 设置已全部配置但无法正常工作

ssl - Shopify SSL 不适用于 CloudFlare?

php - 将 Xdebug 从 php-fpm 和 nginx 容器中分离出来

python - Gunicorn-Django : django project not found

django-debug-toolbar 不会从生产服务器显示

amazon-s3 - 带有 CloudFlare 的 S3 存储桶 : Prevent Hotlinking

redirect - Cloudflare 和 nginx : Too many redirects

http - Cloudflare 不考虑边缘缓存 TTL 值