目前项目中的情况是,1台slb负责流量按照域名分发到不同的服务器,同时slb后端有一台 nginx(这个搭配很骚气)负责slb做不了的代理等操作,因为slb的80端口重定向如果已修改,那么所有域名都会生效,这不是我想看到的结果,我只想要某些指定的域名强制跳转!

常规的操作通常是配置一个80端口,以及一个443端口,当访问80端口时就返回301跳转到https

说一下思路,因为slb访问nginx是只有一个端口,所以在这个里面照抄网上的配置肯定不行,会无限重定向(即重定向到前端通过https访问后,slb又将https转换为http请求了,然后又被重定向,如此循环),所以需要获取前端用户访问https这一层的协议,通过勾选slb的配置可以将这个值放到header传给nginx 在这里插入图片描述 如果你想当然的在nginx里面通过$X-Forwarded-Proto去获取值,那你势必会像我一般折腾半天,我就直接告诉你,首先 nginx是支持读取非nginx标准的用户自定义header的,但是需要在http或者server下开启header的下划线支持:

underscores_in_headers on;

比如我们自定义header为X-Forwarded-Proto ,通过nginx获取该header时需要这样: $http_x_forwarded_proto; 小写且中横线变成了下划线,而且前面多了个http_哦

    server {
        listen	80;
        server_name trace-s.xxxxxx.com;
        server_name_in_redirect off;
		
		access_log	/abc/c7a8/logs/traceability_cd_access.log main;
		error_log	/abc/c7a8/logs/traceability_cd_error.log;

		if ($http_x_forwarded_proto = http ) {
			return 301 https://$host$request_uri;
			# rewrite ^(.*)$ https://${server_name}$1 permanent; 
		}

        root	/abc/c7a8/traceability_cd;
        index	index.html;
		
    }
	

关键点为

if ($http_x_forwarded_proto = http ) {
			return 301 https://$host$request_uri;
			# rewrite ^(.*)$ https://${server_name}$1 permanent; 
}

测试通过,完成!