一般情况下,我们会在nginx.conf中配置absolute_redirect ,server_name_in_redirect和port_in_redirect,以便到达个性化的重定向功能。其中absolute_redirect控制Location url的生成方式。
-
absolute_redirect设置成on,则生成绝对路径作为Location url。
-
absolute_redirect设置成off,则生成相对路径作为Location url。
只有absolute_redirect设置为on时,另外两个配置才会生效。
-
server_name_in_redirect为on时,使用Nginx配置文件中的server_name作为Location url中的host,否则使用用户请求url中的主机名作为host;
-
port_in_redirect设置为on时,使用nginx监听的端口来构造Location url,否则不设置port。
因此,上述三个配置项共同控制了Location url的结果,例如: “Location: http://server_name:port/index/”。 这三项配置的默认值是absolute_redirect=on,server_name_in_redirect=off,port_in_redirect=on。因此默认的Location url将是 “www.test.com/index/” 。
回到最开始的问题,https访问跳转到http的原因便可以梳理清楚了,作为静态资源服务器的Nginx设置了301状态码,并且由于它监听的是80端口和使用http协议,假设浏览器访问 “www.test.com/index” ,那么默认构造的Location url便是 “www.test.com/index/” ,并且API网关会直接将该响应写回给浏览器。浏览器收到301状态码的响应后,解析出响应头的Location值,然后进行跳转。过程如下图所示:
2.解决方案
最简便的解决方法便是,设置absolute_redirect为off,构造相对路径作为Location url,示例如下:
server {
listen 80;
设置相对url重定向
absolute_redirect off;
server_name localhost;
charset utf-8;
access_log logs/access.log main;
error_log logs/error.log;
large_client_header_buffers 4 16k;
client_max_body_size 300m;
client_body_buffer_size 128k;
location / {
index index.html;
root /var/www/index/;
}
}
复制代码
这样以后,对于 “www.test.com/index” 的请求,Location响应头的值将等于 /index/。
最后
金三银四到了,送上一个小福利!
45308)]
[外链图片转存中…(img-4v3RkAY5-1714431645309)]
[外链图片转存中…(img-PKLqs5pP-1714431645309)]