Loading

Nginx 静态站点配置不对导致301跳转的坑

背景

  是这样的,我们前端服务器统一的入口是 kong网关 ,我们还有一个Nginx静态资源站点:static.mysite.com,根配置如下:

location / {
    root  /home/website/static/;
    index  index.html;
    try_files $uri $uri/ /index.html;
}

可以看到我的静态站点root 是/home/website/static/

然后我站点下面有多个文件夹:

static1
static2

vue1

vue2

...

那么我的访问地址是:

http://static.mysite.com/static1/
http://static.mysite.com/static2/ 
...

现需求是

我们的kong网关会绑定多个域名的,比如 api.mysite.comhealth.mysite.com等,我们需要把静态站点部署到静态资源站点,然后由kong网关直接配置指定站点链接

比如我们静态站点链接是: http://static.mysite.com/static1/

而我们的需求是:

http://health.mysite.com/path1/index.html

http://health.mysite.com/path1/path2/static1/index.html

http://api.mysite.com/path1/index.html

...

随便配

坑来了

然后现在需要部署前端地址是 :http://health.mysite.com/static1/

我的kong网关配置

services:

image-20210720100011157

对应的routes:

image-20210720100146368

访问

http://health.mysite.com/static1

都会立刻301到

http://static.mysite.com/static1/

苦恼不已,百思不得其 姐

原因

再看一遍static.mysite.com Nginx配置

location / {
    root  /home/website/static/;
    index  index.html;
    try_files $uri $uri/ /index.html;
}

注意最后一行

静态资源站点最后是一定要带'/'的,不带的话nginx会做一个内部的301跳转

http://static.mysite.com/static1

301 到

http://static.mysite.com/static1/

这就是上面说到301的原因,是我自己没理解透坑自己的地方。

解决

只需要保证到达 http://static.mysite.com/static1/ 路径是这样即可 不要 http://static.mysite.com/static1 这种形式。

在kong网关中可以这样配置

方法1

公用service

service

image-20210720101331041

route

image-20210720101433061

这种方式的缺点就是前端访问地址也必须/结尾,不然404;

优点的配置方便;

方法2

每个route都配置一个service

service:

image-20210720101637105

route:

image-20210720101658548

优点是url好看不需要/结尾;

缺点是配置麻烦一点;

posted @ 2021-07-20 10:34  乔达摩(嘿~)  阅读(1181)  评论(0编辑  收藏  举报