写在前面
最近部署一个测试项目一直遇到一个坑,先贴代码
接口代码
@RestController
@RequestMapping("/api")
public class TestController {
@Value("${server.port}")
private String serverPort;
@RequestMapping(value = "/t1", method = RequestMethod.GET)
public BaseRestResponse getPort() {
BaseRestResponse response = new BaseRestResponse();
response.setMsg(serverPort);
return response;
}
}
前端代码
<template>
<div class="hello">
<h1>已经成功加载页面</h1>
<h1>{{ msg }}</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
msg: ''
}
},
methods: {
getMethod() {
this.$axios.get("/api/t1")
.then(res => {
this.msg = res.data.msg
})
.catch(err => {
})
},
},
mounted() {
this.getMethod()
}
}
</script>
<style scoped>
</style>
以上的配置,在本地通过idea跑项目,然后运行,可以完美访问的
问题出现
然而将前后端项目部署到服务器上之后,配置了nginx代理前端,就访问不到了
接口访问正常
前端静态页面访问正常,但是接口请求不到
nginx配置
worker_processes 1;
events {
worker_connections 65535;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 9000;
server_name _;
location / {
root /home/project/nginxTest/pc;
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
location /api/ {
proxy_pass http://120.78.229.191:9095/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
问题找了好久都没有解决,因为本地都可以访问,不可能是代码存在问题,一定是nginx的配置哪里错了,但是这个配置是从其他项目cv过来的,一直没找到问题。
问题解决
两种方法解决
方法1:在proxy_pass后面也加上api/
worker_processes 1;
events {
worker_connections 65535;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 9000;
server_name _;
location / {
root /home/project/nginxTest/pc;
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
location /api/ {
proxy_pass http://120.78.229.191:9095/api/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
方法2:去掉location的/api/后面的“/”和proxy_pass后面的“/”
worker_processes 1;
events {
worker_connections 65535;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 9000;
server_name _;
location / {
root /home/project/nginxTest/pc;
try_files $uri $uri/ /index.html;
index index.html index.htm;
}
location /api {
proxy_pass http://120.78.229.191:9095/api;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
个人理解
nginx路径覆盖的规则,proxy_pass 最后有 / 的话 location 也得有 / ,location 后面没杠的情况下 /api 这样会自动向proxy_pass 最后补上后缀,带上 / 就不会补了。