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

时间:2017-09-13 12:58:51

标签: nginx nginx-location nginx-reverse-proxy

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

现在我收到错误:400 Bad Request普通HTTP请求已发送到HTTPS端口

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

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

3 个答案:

答案 0 :(得分:3)

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

server {
    listen 80;
    server_name myserver.com;

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

答案 1 :(得分:0)

这可能听起来很简单,但您是否尝试添加" https://"在你输入的域名前面?我发现默认设置总是简单的" http"请求。

答案 2 :(得分:0)

好吧,使用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

中的“错误处理”部分