Nginx反向代理:将所有http请求重定向到https

Nginx reverse proxy : Redirect all http requests to https

我在端口 5000 上有一个带 Nginx 运行 的反向代理,我想将所有到达端口 5000 的请求重定向为 https 请求。

现在我收到错误:400 Bad Request The plain HTTP request was sent to HTTPS port

server {
           listen 5000 ssl;
           server_name myserver.com;

           location / {
               proxy_pass                 http://127.0.0.1:8080;
               proxy_set_header           X-Real-IP   $remote_addr;
               proxy_set_header           X-Forwarded-For  $proxy_add_x_forwarded_for;
               proxy_set_header           X-Forwarded-Proto  $scheme;
               proxy_set_header           X-Forwarded-Server  $host;
               proxy_set_header           X-Forwarded-Host  $host;
               proxy_set_header           Host  $host:5000;


               add_header 'Access-Control-Allow-Methods' 'GET, POST';
               add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
               add_header 'Access-Control-Allow-Credentials' 'true';

               # here comes the basic auth, after the options part
               auth_basic            'Restricted';
               auth_basic_user_file  path/to/.htpasswd;

           }

           ssl    on;
           ssl_certificate    path/to/crt;
           ssl_certificate_key    path/to/key;
       }

好吧,我尝试添加

 if ($scheme != "https") {
    rewrite ^ https://$host$request_uri permanent;
 }

 if ($scheme != "https") {
     return 301 https://$host$request_uri permanent;
 }

似乎没有什么可以解决问题。我应该怎么做才能解决这个问题?

这听起来很简单,但是您是否尝试过在您输入的域名前面添加"https://"?我发现默认值始终是一个普通的 "http" 请求。

假设 http 流量来自端口 80,您可以通过添加额外的服务器块侦听此端口来重定向到 https:

server {
    listen 80;
    server_name myserver.com;

    location / {
        return 301 https://myserver.com$request_uri;
    }
}

好吧,使用 error_page 似乎对我有用。

  server {
       listen 5000 ssl;
       server_name myserver.com;
       error_page 497 https://$host:5000$request_uri;
       ..
       ..
    }

要了解有关 497 的更多信息,请查看 http://nginx.org/en/docs/http/ngx_http_ssl_module.html

中的 "Error Processing" 部分