2012-05-03 22 views
19

服務器聲明:https重定向的rails應用程序後面的代理?在我的nginx.conf

listen  1.2.3.4:443 ssl; 
    root /var/www/myapp/current/public; 
    ssl on; 
    ssl_certificate /etc/nginx-cert/server.crt; 
    ssl_certificate_key /etc/nginx-cert/server.key; 
    location/{ 
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
      proxy_set_header Host $http_host; 
      proxy_redirect off; 

      if (!-f $request_filename) { 
      proxy_pass http://upstreamy; 
      break; 
      } 
    } 

在nginx.conf上游聲明:

upstream upstreamy { 
    server unix:/var/www//myapp/shared/sockets/unicorn.sock fail_timeout=0; 
} 

這工作得很好,MYAPP可達爲https://somehost

,但應用程序正在產生HTTP url的重定向,所以例如當用devise進行身份驗證時,/被重定向到http://somehost/user/sign_in而不是https(從rails應用程序的角度來看,它無論如何都是http)。

我試圖

proxy_pass https://upstreamy; 

但只是試圖nginx的和運行Rails應用程序野牛之間的通信進行加密。

我也試過,在application_helper.rb:

# http://stackoverflow.com/questions/1662262/rails-redirect-with-https 
def url_options 
    super 
    @_url_options.dup.tap do |options| 
    options[:protocol] = Rails.env.production? ? "https://" : "http://" 
    options.freeze 
end 

但似乎不起作用。

如何解決這個問題?

編輯:所以,目標不是要讓rails應用程序需要ssl,要麼是被迫使用ssl;目標是讓導軌應用程序在重定向時生成https:// url ...(我認爲所有其他url都是相對的)。

回答

42

您需要添加下面一行:

proxy_set_header X轉發 - 協議HTTPS;

location/{ 
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
     proxy_set_header Host $http_host; 
     proxy_set_header X-Forwarded-Proto https; 
     proxy_redirect off; 

     if (!-f $request_filename) { 
     proxy_pass http://upstreamy; 
     break; 
     } 
} 
+1

謝謝,完美的作品! –

+0

太棒了!設置nginx會非常痛苦。非常痛苦...... :) –

+0

我無法使用proxy_set_header,但我只是將所有內容轉發給我的代理,用於「發佈」方法並重寫get的url。迄今爲止工作得很好。 – nembleton

-2

你可以通過:protocol => "https",到redirect_to的。

您可以通過添加此設置爲默認值以下,以application.rb中

Rails.application.routes.default_url_options[:protocol]= 'https' 

參考:https://stackoverflow.com/a/6101147/446203

+0

這不透明,將應用程序代碼連接到特定的部署配置。 – eprothro

相關問題