Nginx 配置:文件不存在时返回指定内容

📒 Nginx 配置:GeoJSON 文件不存在时返回空 FeatureCollection

✅ 目标示例

当访问 /geojson/xxx.geojson 文件不存在时,返回如下空 GeoJSON 格式:

{
  "type": "FeatureCollection",
  "features": []
}

🛠 方案一:直接返回空 JSON 字符串(推荐)

Nginx 配置

location /geojson {
    gzip on;
    gzip_types application/octet-stream application/json application/javascript application/geo+json;
    alias /data/Polar/geojson/geojson-data;

    error_page 404 = @geojson_not_found;
}

location @geojson_not_found {
    default_type application/geo+json;
    return 200 '{"type":"FeatureCollection","features":[]}';
}

优点

  • 无需额外文件
  • 简洁、易部署

🛠 方案二:返回本地 default.geojson 文件

步骤

  1. 创建文件 /data/Polar/geojson/geojson-data/default.geojson,内容如下:
{
  "type": "FeatureCollection",
  "features": []
}
  1. 修改 Nginx 配置:
location /geojson {
    gzip on;
    gzip_types application/octet-stream application/json application/javascript application/geo+json;
    alias /data/Polar/geojson/geojson-data;

    try_files $uri /geojson/default.geojson;
}

优点

  • 更灵活,适合后期需要返回更复杂默认内容的情况

📌 注意事项

  • alias 路径和 try_files 中路径需配套使用。
  • gzip_types 中需包含 application/geo+json
  • default_type 设置为 application/geo+json 可明确 MIME 类型。
posted @ 2025-04-21 10:08  槑孒  阅读(51)  评论(0)    收藏  举报