How to make nginx redirect based on the value of a header?

拜拜、爱过 提交于 2020-06-09 07:54:07

问题


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.

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.

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?


回答1:


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



回答2:


Try using map directive: http://nginx.org/en/docs/http/ngx_http_map_module.html#map

Something like that...

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

This code is abstract, but you can try tht way...



来源:https://stackoverflow.com/questions/26223733/how-to-make-nginx-redirect-based-on-the-value-of-a-header

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!