![为什么带有斜杠的查询可以工作,但是在我的 Nginx 配置中没有尾随斜杠会出现 404 错误?](https://linux22.com/image/1560691/%E4%B8%BA%E4%BB%80%E4%B9%88%E5%B8%A6%E6%9C%89%E6%96%9C%E6%9D%A0%E7%9A%84%E6%9F%A5%E8%AF%A2%E5%8F%AF%E4%BB%A5%E5%B7%A5%E4%BD%9C%EF%BC%8C%E4%BD%86%E6%98%AF%E5%9C%A8%E6%88%91%E7%9A%84%20Nginx%20%E9%85%8D%E7%BD%AE%E4%B8%AD%E6%B2%A1%E6%9C%89%E5%B0%BE%E9%9A%8F%E6%96%9C%E6%9D%A0%E4%BC%9A%E5%87%BA%E7%8E%B0%20404%20%E9%94%99%E8%AF%AF%EF%BC%9F.png)
针对以下 nginx 配置:
upstream search {
least_conn;
server www.google.com:80
max_fails=1
fail_timeout=10
weight=1;
keepalive 12;
}
limit_req_zone $binary_remote_addr zone=search:1m rate=10r/s;
resolver 127.0.0.1;
server {
listen 80 default_server;
charset utf-8;
server_name _;
access_log /dev/stdout json;
location @search {
# Deny requests that do not match allowed methods REGEX
if ($request_method !~ ^GET$ ) {
return 405;
}
set $proxy_uri $uri;
if ($proxy_uri ~ ^/[^/]+(/.*)$ ) {
set $proxy_uri "$1";
}
# Deny requests that do not match allowed paths REGEX
if ($proxy_uri !~ ^.*(\?|$) ) {
return 403;
}
# Rate Limit Requests
limit_req zone=search burst=10 nodelay;
# Adding new client_max_body_size service attribute per location
client_max_body_size 1m;
proxy_http_version 1.1;
# Set CORS Headers
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
proxy_set_header Origin "";
proxy_set_header Connection "";
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://search$proxy_uri$is_args$args;
}
location /search/ {
client_max_body_size 1m;
# send request to the named location for the service
error_page 418 = @search; return 418;
}
# Default location for unmatched requests
location / {
return 404;
}
location = /health {
return 200;
}
}
跑步
curl -siL -H 'Host: www.google.com' '127.0.0.1/search/'
返回 200
但
curl -siL -H 'Host: www.google.com' '127.0.0.1/search'
返回 404。
我如何使带和不带斜线的返回值都为 200?
答案1
我曾经有过类似的经历,不过是在不同的环境中,所以你可能需要自己测试一下以验证。例如,在 Apache 上,如果你配置为允许CORS
(跨源资源共享),它似乎只有在有尾部斜杠时才有效。我能想到的唯一解释是,服务器需要能够明确区分目录和文件(毕竟,文件可以没有扩展名,最终看起来像目录,目录名也可以有一个点,最终看起来像文件)以允许或禁止CORS
,因此,几乎每个在服务器上运行的查询都是如此。进行测试并验证在你的情况下是否如此。