2015-02-24 39 views
1

如果您想折磨某人直到時間結束,只需讓他們配置Django和Nginx X-Accel-Redirect即可。這實際上是不可能的,我一直在努力幾天。Django Nginx X-Accel重定向Webfaction上的受保護文件

我想只允許某些文件在web上使用Nginx在django的登錄視圖下載。這是我有:

自定義Nginx應用程序偵聽/靜態下端口27796。這是conf。

http { 
include  mime.types; 
default_type application/octet-stream; 
sendfile  on; 
keepalive_timeout 65; 
server { 
    listen  27796; 
    server_name myurl.com; 
    root /home/ucwsri/webapps/static_media_ucwsri_nginx; 

    location/{ 
     autoindex on; 
    } 

    location ^.*/protected-files { 
     internal; 
     alias /home/ucwsri/webapps/static_media_ucwsri_nginx/protected; 
    } 

所有靜態內容是在/ home/ucwsri/webapps /下static_media_ucwsri_nginx,並正在通過正確的Nginx這個應用投放。

我想保護的文件在這裏:

/home/ucwsri/webapps/static_media_ucwsri_nginx/protected 

哪個^ * /保護的文件在Nginx的阻擋位置中列出的別名。

的觀點只是使這樣的HTTP響應:

response = HttpResponse() 
url = "/static/protected-files/some-file.pdf" 
response['X-Accel-Redirect'] = url 

return response 

凡 '一些-file.pdf' 文件中

/home/ucwsri/webapps/static_media_ucwsri_nginx/protected 

無論我嘗試從我的Nginx獲得404試圖存在時將該文件作爲發送到該視圖的POST請求。我嘗試了所有我能想到的,每個位置組合塊,沒有任何工作。總是一個404.

有人請讓我擺脫我的痛苦,告訴我我做錯了什麼。對於看似簡單的事情來說,這確實很殘酷。

回答

1

首先,你的location ^.*/protected-files是胡說。我想,你已經錯過了~修飾符,但即使在這種情況下,它也沒用。

二,你沒有保護/protected/文件夾。直接請求到/protected/some-file.pdf將下載該文件沒有任何保護。

三,您在X-Accel-Redirect中有/static/protected-files/some-file.pdf,但您之前沒有提及任何static文件夾。

所以,我建議以下配置:

server { 
    listen  27796; 
    server_name myurl.com; 
    root /home/ucwsri/webapps/static_media_ucwsri_nginx; 

    location/{ 
     autoindex on; 
    } 

    location ^~ /protected/ { 
     internal; 
    } 

而且Django的應該是:

response = HttpResponse() 
url = "/protected/some-file.pdf" 
response['X-Accel-Redirect'] = url 

return response 

摘要:

  • 保護真正的文件夾。
  • X-Accel-Redirect是URI,就好像用戶把這個URI放在瀏覽器的地址欄中一樣。唯一的區別是,internal將允許訪問X-Accel-Redirect,同時禁止直接從瀏覽器訪問用戶。