解决请求URL结尾不带"/"时出现301重定向的问题

865 阅读1分钟

用户在浏览器访问www.quicktable.io/appswww.quicktable.io/apps/ 时都是可以正常访问到页面,但是在一些场景下比如:搜索引擎爬虫,iframe页面嵌套时会遇到请求有重定向而导致无法加载的问题。

现象是这样的

  1. 请求URL是: www.quicktable.io/apps
  2. 301重定向到 http://www.quicktable.io/apps/
  3. 301重定向到 https://www.quicktable.io/apps/

image.png

疑问

  1. 为什么url会自动加上/
  2. https为什么会重定向到http

关于Nginx的自动跳转

nginx的配置如下

location /apps  {
      alias /usr/local/nginx/static/;
      index index.html;
      add_header Cache-Control no-cache;
      add_header Pragma no-cache;
    }

当访问 www.quicktable.io/apps 时, 由于nginx在/usr/local/nginx/static/目录下没有找到apps这个文件,nginx就会自动进行301重定向并加上/。

image.png image.png

解决方法

利用 try_files

try_files 按指定顺序检查文件是否存在,并使用第一个找到的文件进行请求处理,其中 file 遵循该 context 中所提供的 root / alias 为根目录,往后寻找相对路径的结果。

try_files $uri  $uri/index.html /apps/index.html;

当用户请求www.quicktable.io/apps 时,$uri就是/apps

  1. try_files 会尝试到aliasroot指定的目录下找这个文件,如果存在{alias}/apps的文件,就直接把这个文件的内容发送给用户。

  2. 没有找到apps的文件,然后就到 $uri/,也就是看有没有{alias}/apps/的目录。(本例通过$uri/index.html 避免重定向了)

  3. 如果还没有找到,就会到最后一个选项,ningx内部发起一个http请求到www.quicktable.io/apps/index.…

修改 absolute_redirect

语法: absolute_redirect on | off;
默认: on 绝对重定向 
可用上下文: `http``server`,`location

配置相对路径重定向

 location /apps  {
      alias /usr/local/nginx/static/;
      index index.html;
      absolute_redirect off;
      add_header Cache-Control no-cache;
      add_header Pragma no-cache;
    }

image.png