后端通过nignx代理转发,提供接口供前端在防火墙外访问
如题:
前端页面通过防火墙nat到外网,而后端接口均在内网。导致外网访问前端页面无法获取后端接口。
解决方案:
通过nginx代理转发后端接口路径。
在前端axios接口中,配置统一的baseurl为/api。
在nginx配置文件加上/api的location,并设置转发内网的后端url。
server {listen 80;server_name 100.100.100.100; # 更换为您的域名# 根目录和索引文件root /usr/share/nginx/html; # 确保这是您的静态文件路径index index.html index.htm;# 为根目录提供文件location / {try_files $uri $uri/ /index.html;}# 防止 .htaccess 和 .htpassword 等隐藏文件的访问location ~ /\. {deny all;}# 新增:后端API代理配置location /api/ {proxy_pass http://192.168.1.100:8080/; # 后端服务器地址proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;}# 可选:静态资源缓存配置location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {expires 7d;add_header Cache-Control "public, no-transform";}
}
需要注意的是,前端axios的baseurl不可写死后端url,不可为http://xxxx:8080等url,也不可为http://xxxx.com等域名,设置IP和域名后nginx无法完成代理转发。所以必须为/api等,让url默认跟随前端url前缀,才可以完成nginx转发。