rest - 如果后端离线,则不要提供静态文件
问题描述
我有以下 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 后端的请求。当后端离线时,如何以相同的方式将请求重定向到我的静态网站?
解决方案
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。
由于您现在总是在执行额外的请求,因此此方法可能会对性能产生一些影响,但这似乎是检查您的服务是否在线的内在要求。
推荐阅读
- http - 无法访问 https 和非 www 重定向到测试 httpd
- python - 如何通过 Jenkins Python API 获得成功构建的进度
- pdf - 在 PDF 中搜索文本 - 双重结果
- openshift - Openshift 4.3 裸机安装
- c - C 语言:将数据从一个 typedef 结构复制到另一个并返回一个值
- ios - Gigya Swift SDK:“无效的请求签名”
- laravel - 如何在数据透视表 laravel 中存储数据附加列
- jquery - 隐藏和显示表格列并一起显示所有列
- c++ - GMock 调用错误的模拟函数
- c# - 将新的 .NET CORE 加载到 Visual Studio 2017 c# .NET CORE 项目中的问题