NGINX:当proxy_pass失败时提供静态文件

时间:2014-08-25 15:12:26

标签: nginx

我有一个运行nginx的前端,它向运行Web服务的后端代理请求。 如果后端服务已关闭,我想提供一个静态文件。

这是我正在使用的配置文件:

location ~ /api/admin {
        rewrite /xxxx/(.+) /$1 break;
        error_page 404 502 =200 /themes/yyyy/themes.json;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        add_header Access-Control-Allow-Credentials true;
        add_header Access-Control-Allow-Origin '*';
        add_header Access-Control-Allow-Methods 'GET, POST';
        proxy_intercept_errors on;
        proxy_pass http://xxxx;
}

location = /themes/yyyy/themes.json {
        rewrite /themes/yyyy/themes.json /api/admin/thematics/edito;
}

我打电话的时候:

http://url/themes/geoportail/themes.json

我收到来自nginx的502错误,而不是200和静态文件......

2014/08/25 17:02:35 [error] 13551#0: *6719 connect() failed (111: Connection refused) while connecting to upstream, client: 160.92.103.160, server: uri, request: "GET /themes/yyyy/themes.json HTTP/1.1", upstream: "http://IP:PORT/api/admin/thematics/edito", host: "", referrer: ""

1 个答案:

答案 0 :(得分:3)

我发布了一个我发现的解决方案,随意提出更优雅的解决方案。

location ~ /api/admin {
        rewrite /xxxx/(.+) /$1 break;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        add_header Access-Control-Allow-Credentials true;
        add_header Access-Control-Allow-Origin '*';
        add_header Access-Control-Allow-Methods 'GET, POST';
        proxy_intercept_errors on;
        proxy_pass http://xxxx;
        error_page 404 502 503 504 =200 @statictheme;
}

location @statictheme {
    try_files $uri /themes/yyyy/themes.json last;
}

location = /themes/yyyy/themes.json {
        rewrite /themes/yyyy/themes.json /api/admin/thematics/edito;
}