nginx - 由于某种原因,位置指令似乎不起作用
问题描述
几天前,我在 k8s 部署中偶然发现了 Nginx。由于我对 Nginx 比较陌生,所以我想了解它是如何工作的——所以我进行了自己的开发部署。
问题是我无法nginx.conf
按预期工作:
- 访问
/healthz
端点时,返回200
(k8s 的健康检查) - 将任何其他流量重定向
http
到https
这是我目前的nginx.conf
:
server {
listen 80;
listen [::]:80;
server_name _;
location /healthz {
return 200 "healthy";
}
return 301 https://$host$request_uri;
access_log off;
error_log /usr/share/nginx/web/logs/http_error.log error;
}
server {
listen 443 ssl http2 default_server;
listen [::]:443 ssl http2 default_server;
server_name company.com;
root /usr/share/nginx/web;
index index.html;
access_log off;
error_log /usr/share/nginx/web/logs/ssl_error.log error;
ssl_certificate /usr/share/nginx/web/cert/company.crt;
ssl_certificate_key /usr/share/nginx/web/cert/company.key;
}
我得到的响应(我已经删除了 IP 地址):
[error] 28#28: *2 open() "/usr/share/nginx/web/healthz" failed (2: No such file or directory), client: xx.xx.xx.xx, server: company.com, request: "GET /healthz HTTP/2.0", host: "xx.xx.xx.xx", referrer: "http://xx.xx.xx.xx:80/healthz"
请求在端口
80
上,/healthz
但不是返回200
,而是重定向到https
失败的服务器
在这一点上我真的不知道为什么它不起作用,所以请,即使是一些愚蠢的错误,请随时指出!
我在这里做错了什么?
解决方案
ngx_http_rewrite_module
上下文中处理的所有指令server
(包括return
一个)都在上下文中的相同指令之前执行location
。您应该定义两个位置以实现所需的行为:
server {
listen 80;
listen [::]:80;
server_name _;
access_log off;
error_log /usr/share/nginx/web/logs/http_error.log error;
location / {
return 301 https://$host$request_uri;
}
location /healthz {
return 200 "healthy";
}
}
推荐阅读
- python - 在 Colab 中安装 MeshPy
- python - 无法加载自定义数据集
- react-native - Android 依赖 'com.airbnb.android:lottie' 有不同版本的编译(2.5.5)和运行时(2.5.6)类路径
- autocomplete - 如何使用 Map 函数解析这个 javascript 数组?
- javascript - 如何可视化网站的 js 依赖项
- android - 如何在多个图像视图中设置多个图像
- java - My app keeps on crashing and I am not able to see what the problem is
- mysql - 内连接显示输出中的重复行。它多次显示数据
- ionic-framework - 使用 Ionic 的自动检测应用程序
- json - 不能使用“encoding/json”覆盖 eagle(类型接口 {})