edit-icon download-icon

Simple routing - force to redirect from HTTP to HTTPS

Last Updated: Jan 12, 2018

You can access the website you needed by using HTTPS according to Simple routing - change HTTP to HTTPS. For example, use the following application template:

  1. app:
  2. ports:
  3. - 80/tcp
  4. image: 'registry.cn-hangzhou.aliyuncs.com/linhuatest/hello-world:latest'
  5. labels:
  6. # Here only the http/https/ws/wss protocol
  7. aliyun.routing.port_80: "http://www.example.com"
  8. restart: always

After configuring the Server Load Balancer, access the HTTPS website.

1

You can also configure to force the HTTP request to redirect to HTTPS.

The following example configures an Nginx container and adds the rewrite rules to the configuration file, namely, when request http://www.example.com is received, 301 is returned and the request is automatically redirected to https://www.example.com.

Log on to each machine in the cluster. Create the Nginx configuration file /ngx/nginx.conf, which will be mounted to the Nginx container as a volume. The /ngx/nginx.conf is as follows:

  1. user nginx;
  2. error_log /var/log/nginx/error.log warn;
  3. pid /var/run/nginx.pid;
  4. events {
  5. worker_connections 65535;
  6. }
  7. http {
  8. include /etc/nginx/mime.types;
  9. default_type application/octet-stream;
  10. log_format main '$remote_addr - $remote_user [$time_local] "$request" '
  11. '$status $body_bytes_sent "$http_referer" '
  12. '"$http_user_agent" "$http_x_forwarded_for"';
  13. access_log /var/log/nginx/access.log main;
  14. keepalive_timeout 65;
  15. gzip on;
  16. server {
  17. listen 80;
  18. server_name localhost;
  19. return 301 https://$host$request_uri;
  20. }
  21. }

The Nginx container template is as follows:

  1. nginx:
  2. ports:
  3. - 80:80/tcp # Map to port 80 of the host.
  4. image: 'nginx:latest'
  5. labels:
  6. aliyun.global: true # Deploy an Nginx container on each machine to guarantee the high availability.
  7. volumes:
  8. - /ngx/nginx.conf:/etc/nginx/nginx.conf
  9. restart: always

The Server Load Balancer settings for the cluster is as follows (frontend port 80 > backend port 80, namely, Server Load Balancer frontend port 80 > backend Elastic Compute Service (ECS) instance port 80):

1

When you access http://www.example.com, the returned HTTP is as follows. This means the request is correctly redirected to https://www.example.com.

3

Thank you! We've received your feedback.