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

缺點是配置麻煩一點;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM