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好看不需要/結尾;

缺點是配置麻煩一點;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章