2013-08-30 29 views
2

現在我有一個啓用了SSL的網站。 SSL處於ELB級別,所以apache http服務器永遠不會看到它。我試圖做到這一點,所以Apache將強制所有請求有https,因此沒有http請求正在作出。我讀的SO包括這幾個其他職位:ELB上的SSL,但設置了Apache

Django and SSL question

https://serverfault.com/questions/410542/disable-https-for-certain-path-in-nginx-results-in-instance-behind-elb-going-int

http://www.acmedata.in/2012/08/31/how-to-host-a-django-app-behind-elb-with-ssl/

我可以利用ELB配置的呢?或者是否必須從ELB中刪除私鑰等,並將其全部放在Web服務器級別?我無法找到這方面的進一步資料...

回答

5

您可以通過添加這樣的重寫規則到你的Apache配置強制HTTPS:

<VirtualHost *:80> 
    ... 
    RewriteEngine On 
    RewriteCond %{HTTP:X-Forwarded-Proto} !https 
    RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=permanent] 
    ... 
</VirtualHost> 

這裏的關鍵是X-Forwarded-Proto頭。 ELB處理https並將請求轉發給Apache,並在此過程中添加此標頭。重寫規則檢查這個標頭只重定向不是來自ELB的http請求。

2

您可以在Django的層面解決這個問題,這是我用:

from django.http import HttpResponsePermanentRedirect 
from django.conf import settings 


class SecureRequiredMiddleware(object): 
    def __init__(self): 
     self.paths = getattr(settings, 'SECURE_REQUIRED_PATHS') 
     self.enabled = self.paths and getattr(settings, 'HTTPS_SUPPORT') 

    def process_request(self, request): 
     if self.enabled and not request.is_secure(): 
      full_path = request.get_full_path() 

      for path in self.paths: 
       if full_path.startswith(path): 
        secure_url = request.build_absolute_uri(full_path).replace(
         'http://', 'https://') 
        return HttpResponsePermanentRedirect(secure_url) 

是添加到文件中並指向它與您中間件設置。然後你需要添加兩個設置項。首先是所謂的SECURE_REQUIRED_PATHS,它應該是URL的像這樣的列表:

SECURE_REQUIRED_PATHS = [ 
    '/login', # require HTTPS for any URL starting with `/login` 
    '/account', # require HTTPS for any URL starting with `/account` 
    '/',  # require HTTPS for all URLs 
] 

第二個應該被稱爲一個標誌HTTPS_SUPPORT

HTTPS_SUPPORT = True 

然後每當有用戶訪問你的SECURE_REQUIRED_PATHS與網址HTTP,它們將被重定向到相應的HTTPS。

+0

但這個創造https鏈接在頁面上?或者它只是重定向每個請求?我寧願不這樣做...... – KVISH

+0

它只會重定向到您的SECURE_REQUIRED_PATHS設置中的URL的請求。將證書放在應用程序節點而不是ELB上是非選項iirc,因爲ELB需要能夠在實際進行負載平衡之前解密SSL流。 –

+0

我明白,但這不是正確的方法。正確的方法是另一種解決方案......因爲它會在http服務器上重寫URL。此代碼將首先到達應用程序,然後它將重新運行每個請求(只要它在所需的https路徑中)。 – KVISH