2013-02-21 60 views
2

我試圖從應用程序nginx反向代理靜態文件,如果應用程序正在爲他們提供服務,否則自己服務。目前,我有這樣的配置:nginx try_files從代理的應用程序,然後nginx

upstream app_server { 
    server unix:/tmp/gunicorn.sock fail_timeout=0; 
} 

server { 
    listen   8080; 
    server_name  example.com; 
    access_log  /var/log/nginx.access.log; 
    error_log  /var/log/nginx.error.log; 

    keepalive_timeout 5; 

    location /static { 
     try_files $uri @proxy_to_app; 
     alias  /path/to/__static; 
     sendfile off; 
    } 

    location/{ 
     try_files $uri @proxy_to_app; 
    } 

    location @proxy_to_app { 
     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
     proxy_set_header Host $http_host; 
     proxy_redirect off; 

     proxy_pass http://app_server; 
    } 
} 

如果/path/to/__static不存在的文件這工作;它將請求發送到應用程序服務器。但是,如果這些文件也存在於/path/to/__static中,則nginx會自行處理這些文件。

反轉try_files行(try_files @proxy_to_app $uri)在兩種情況下均失敗。如果客戶端請求/static/css/test.css,應用程序接收請求/css/test.css,它似乎永遠不會嘗試/path/to/__static即使應用程序返回一個404

更新包括完整的配置。

+1

請顯示您的完整配置。可能最有趣的部分是「@proxy_to_app」。 – VBart 2013-02-21 17:11:45

+0

已用完整配置更新 – rouge8 2013-02-21 17:20:39

+0

您是否閱讀過[文檔](http://nginx.org/r/try_files)? 'try_files'指令根本不適合你的任務。您應該使用'error_page'和'proxy_intercept_errors'的組合。 – VBart 2013-02-21 17:39:16

回答

6
location /static/ { 
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; 
    proxy_set_header Host $http_host; 
    proxy_redirect off; 
    proxy_pass http://app_server; 
    proxy_intercept_errors on; 
    error_page 404 =200 /local$uri; 
} 

location /local/static/ { 
    internal; 
    alias /path/to/__static/; 
} 
+0

'error_page 404 =/local/$ uri;'行不起作用。它需要更改爲'error_page 404 = 200/local $ uri;'。 – rouge8 2013-02-21 18:40:18

+0

Yeap,對。我已經解決了答案。 – VBart 2013-02-21 19:26:40