首页 > 解决方案 > 如果后端离线,则不要提供静态文件

问题描述

我有以下 nginx 配置来处理为我的静态网站提供服务并将请求重定向到我的 REST 后端:

server {
    listen 80 default_server;
    server_name _;

    # Host static content directly
    location / {
        root /var/www/html;
        index index.html;
        try_files $uri $uri/ =404;
    }

    # Forward api requests to REST server
    location /api {
        proxy_pass http://127.0.0.1:8080;
    }

}

如果我的 REST 后端脱机,代理模块会返回 HTTP 状态“502 Bad Gateway”,我可以通过添加以下内容将请求重定向到状态页面:

# Rewrite "502 Bad Gateway" to "503 Service unavailable"
error_page 502 =503 @status_offline;

# Show offline status page whenever 503 status is returned
error_page 503 @status_offline;
location @status_offline {
    root /var/www/html;
    rewrite ^(.*)$ /status_offline.html break;
}

但是,这仅适用于直接访问 REST 后端的请求。当后端离线时,如何以相同的方式将请求重定向到我的静态网站?

标签: restnginxwebserver

解决方案


Nginx 确实有一些健康检查和状态监控功能,看起来它们可能是相关的,但我找不到合适的方法来使用它们。

虽然它的预期用例实际上是用于授权,但我发现 nginx 的auth_request模块对我有用:

# Host static content directly
location / {
    # Check if REST server is online before serving site
    auth_request /api/status; # Continues when 2xx HTTP status is returned
    # If not, redirect to offline status page
    error_page 500 =503 @status_offline;

    root /var/www/html;
    index index.html;
    try_files $uri $uri/ =404;
}

它将/api/status在提供静态内容之前作为子请求调用,并且仅当子请求返回 200 范围内的 HTTP 状态时才会继续。服务器离线时似乎返回状态 500。

由于您现在总是在执行额外的请求,因此此方法可能会对性能产生一些影响,但这似乎是检查您的服务是否在线的内在要求。


推荐阅读