前端域名为:a.com
后端域名为:b.com
预期:当访问a.com/api/ 跳转到 b.com/
前端Nginx的配置:
server {
listen 80;
server_name a.com;
root /it/vue/dist/;
location / {
index index.php index.html index.htm;
try_files $uri $uri/ /index.html;
}
location ^~/api/ {
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-NginX-Proxy true;
proxy_pass http://@back/;
}
}
#后端地址
upstream @back{
server b.com;
}
^~/api/表示匹配前缀是api的请求,proxy_pass的结尾有/, 则会把/api/*后面的路径直接拼接到后面,即移除api
注:upstream命名最后加特殊符,要不然在 location ^~/api/ {……} 里,nginx会报语法错误。