2017-09-13 365 views
1

我有一個反向代理,Nginx在端口5000上運行,我希望將所有到端口5000的請求重定向爲https請求。Nginx反向代理:將所有HTTP請求重定向到https

現在我得到的錯誤:400錯誤請求的普通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; 
} 

似乎沒有任何解決問題。我應該怎麼做才能解決這個問題?

+0

的可能的複製[nginx的重定向HTTPS到HTTP](https://stackoverflow.com/questions/3470290/nginx- redirect-https-http) – lifeisfoo

回答

0

這可能聽起來很簡單,但您是否曾嘗試將「https://」添加到您鍵入的域名的前面?我發現默認總是一個普通的「http」請求。

+0

是的,但一段時間後,對於某些請求頁面刷新和'https://'被刪除,我着陸在上面提到的錯誤頁面 – InfamousCoder

+0

然後,下面的答案是你想 - 做一個自動重定向到ssl url。 –

+0

我是否使用位置內的proxy_redirect? – InfamousCoder

2

假設HTTP流量來自通過80端口,就可以通過添加額外的服務器塊監聽到該端口重定向到https:

server { 
    listen 80; 
    server_name myserver.com; 

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