如果后端离线,不要提供静态文件

Don't serve static files if backend is offline

我有以下 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 后端脱机 proxy module returns 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 后端的请求。如何在后端离线时以相同的方式将请求重定向到我的静态网站?

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

虽然它的预期用例实际上是为了授权,但我发现 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 作为子请求调用,并且仅当子请求 return 的 HTTP 状态在 200 范围内时才会继续。服务器离线时似乎return状态为500。

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

我认为这是正确的答案 - 身份验证请求非常适合您希望在返回请求的内容之前 "ping" 后端的任何情况。

我过去对 nginx 服务器使用过类似的方案,我想在代理到 S3 存储桶之前检查 auth header 是否正确。