要使用Nginx代理天地图(Tianditu)服务并解决跨域问题,同时实现缓存功能,可以按照以下步骤配置:
确保已安装Nginx,如果没有安装可以通过以下命令安装(以Ubuntu为例):
sudo apt update
sudo apt install nginx
编辑Nginx配置文件(通常在/etc/nginx/nginx.conf
或/etc/nginx/conf.d/
目录下):
http {
# 启用代理缓存
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=tianditu_cache:10m inactive=7d use_temp_path=off;
server {
listen 80;
server_name your-domain.com; # 替换为你的域名或IP
location /tianditu/ {
# 代理到天地图服务
proxy_pass https://t{s}.tianditu.gov.cn/;
# 解决跨域问题
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
# 缓存配置
proxy_cache tianditu_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 302 7d; # 缓存7天
proxy_cache_valid 404 1m;
# 替换服务器编号(0-7)
proxy_set_header Host "t{s}.tianditu.gov.cn";
rewrite ^/tianditu/(.*) /$1 break;
# 其他代理设置
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Referer https://tianditu.gov.cn/;
# 启用gzip压缩
gzip on;
gzip_types image/png image/jpeg text/plain application/javascript application/x-javascript text/javascript text/xml text/css;
}
}
}
天地图使用t0-t7多个服务器,可以使用Nginx的map功能实现动态选择:
http {
map $request_uri $tianditu_server {
default 0;
}
server {
# ...其他配置...
location /tianditu/ {
proxy_pass https://t$tianditu_server.tianditu.gov.cn/;
# ...其他配置...
}
}
}
配置完成后,检查配置并重载:
sudo nginx -t # 测试配置是否正确
sudo systemctl reload nginx # 重载配置
配置完成后,可以通过以下方式访问天地图服务:
http://your-domain.com/tianditu/vec_w/wmts?...
此配置解决了跨域问题,实现了缓存功能,并且可以负载均衡到天地图的不同服务器。