How to redirect on the same port from http to https with nginx reverse proxy

后端 未结 5 1883
借酒劲吻你
借酒劲吻你 2020-12-24 01:12

I use reverse proxy with Nginx and I want to force the request into HTTPS, so if a user wants to access the url with http, he will be automatically redirected to HTTPS.

5条回答
  •  误落风尘
    2020-12-24 02:13

    This is my approach, which I think is quite clean and allows you to add further locations if needed. I add a test on the $http_x_forwarded_proto property which if true forces all HTTP traffic to HTTPS on a NGINX Reverse Proxy setup

    upstream flask_bootstrap {
        server flask-bootstrap:8000;
    }
    
    server {
        # SSL traffic terminates on the Load Balancer so we only need to listen on port 80
        listen 80;
    
        # Set reverse proxy
        location / {
            proxy_pass http://flask_bootstrap;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $host;
            proxy_redirect http://localhost/;
    
            # Permanently redirect any http calls to https
            if ($http_x_forwarded_proto != 'https') {
                return 301 https://$host$request_uri;
            }
        }
    }
    

提交回复
热议问题