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 文件
步骤
- 创建文件
/data/Polar/geojson/geojson-data/default.geojson,内容如下:
{
"type": "FeatureCollection",
"features": []
}
- 修改 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 类型。

浙公网安备 33010602011771号