1、再用nginx给springboot项目做代理转发时,springboot项目最好不要带项目访问路径。就是别设置
server.servlet.context-path=/crud

我在使用二级域名代理转发时,如果springboot带项目访问路径,但是location 后面和项目访问路径不一致,经常报404错误。
带项目访问路径出错,具体有下面几种情况

(1)localtion /

对应的配置如下

server{
	listen 80;
	server_name test.xxx.online;
	
	location /{
		proxy_set_header Host $host;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_pass http://localhost:85/registration-system;
	}			       	

}

使用nginx -s reload 刷新后使用浏览器访问出错如下。这种情况和下面一种几乎一样,所以直接看下面的。

kibana nginx 地图 nginx location path_html

location /aaa

这里aaa就可以是任意与springboot项目访问路径名不一样的字符串。
对应的配置代码如下。

server{
	listen 80;
	server_name test.XXX.online;
	
	location /aaa{
		proxy_set_header Host $host;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_pass http://localhost:85/registration-system;
	}			       	
		 
 }

使用nginx -s reload 刷新后使用浏览器访问出错过程如下。

kibana nginx 地图 nginx location path_spring_02


具体每个请求的结果

kibana nginx 地图 nginx location path_kibana nginx 地图_03


kibana nginx 地图 nginx location path_spring_04


aaa请求哪里可以看出(具体看图中标出的location那块),好像nginx没有加上端口号,其实在域名后面加上端口号就可以访问了。这种是进行两次请求。第一次状态时302,第二次才是404。

在nginx 的errror.log里面看见对应的错误如下,可以看见,这并没有按照我们的意愿来,它是访问了nginx安装目录html文件夹下面的内容。

3736#8524: *1183 "C:\Student_create\nginx-1.16.1/html/registration-system/index.html" is not found (3: The system cannot find the path specified)
(3)location /(springboot的项目访问路径名)

配置如下

server{
	listen 80;
		server_name test.XXX.online;
	location /registration-system{
		proxy_set_header Host $host;
		proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
		proxy_pass http://localhost:85/registration-system;
	}			       	
		 
}

这种可以成功访问,浏览器结果如下。

kibana nginx 地图 nginx location path_spring_05


放大后看

kibana nginx 地图 nginx location path_html_06


可以看见这里没有向前面两种情况需要跳转导致访问失败。

这种错误应该是我这种刚用nginx的人犯的,经过后来查询资料,这和nginx 的路径映射规则有很大关系。

值得注意的是,如果按照第二篇博客那样修改(如下 加了 /),会使得可以加载网页,但是所有的静态资源都加载不了。可以尝试一下。

proxy_pass http://localhost:85/registration-system/;
(4)我后来又试过,结果多种多样。

下面每种操作都会有不同的结果,而且有时候自相矛盾,千奇百怪。nginx把我这个小白折腾的够呛。

1、比如是否使用upstream
2、使用在访问时加/
3、是否加
			proxy_set_header Host $host;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

总结

配置proxy_pass的时候最好不要加访问路径,如果加的话就把location后面的uri设为和访问路径相同,不然可能会导致各种错误。

关于location 和proxy_pass路径问题,可以参考下面两个博客,但是我得出的结果和他们说的不一样,准确的说是有时候一样,有时候不一样。但是这些博客的说法都是一样的。所以应该是我理解的问题吧。