您可以配置使 HTTP 协议请求强制跳转到 HTTPS 协议。
本例中,创建一个 nginx 容器,监听 http 请求,将所有的 http
请求通过 rewrite 重写到 https上,从而将请求重定向至 https 协议,实现基于
www.example.com 域名的强制跳转。
下面的示例配置了 nginx 容器并将
rewrite 规则写到配置文件中,即如果收到请求 http://www.example.com,则返回
301 且自动跳转到
https://www.example.com。
登录集群中的每台机器,创建 nginx.conf 配置文件,该配置文件将以 volume 形式挂载到容器 nginx
中。cd / ## 返回根目录
mkdir ngx ## 创建 ngx 目录
vim nginx.conf ## 创建 nginx.conf 配置文件
在/ngx/nginx.conf配置文件中输入如下的配置代码。user nginx;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 65535;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
keepalive_timeout 65;
gzip on;
server {
listen 80;
server_name localhost;
return 301 https://$host$request_uri;
}
}
使用编排模板创建 nginx 应用。
nginx
应用的编排模板如下所示。
nginx:
ports:
- 80:80/tcp # 映射到主机的 80 端口
image: 'nginx:latest'
labels:
aliyun.global: true # 每台机器均部署一个 nginx 容器,达到高可用目的
volumes:
- /ngx/nginx.conf:/etc/nginx/nginx.conf
restart: always
配置集群负载均衡的监听规则。
如下图所示(其中,前端 80 端口 > 后端 80 端口,即负载均衡的前端端口 > 后端 ECS 实例的端口
80)。
验证 HTTP 强制跳转到 HTTPS
当您访问 http://www.example.com 时,会自动跳转到
https://www.example.com 。返回的 HTTP
协议内容如下图所示,即完成了正确跳转到 https://www.example.com。
|