Alojamiento de sitios simple con Amazon S3 y HTTPS

Hola amigos!

En este tutorial, le mostraré cómo alojar un sitio web estático con HTTPS en AWS con un dominio personalizado. Todo esto es posible utilizando la capa gratuita de AWS.

Sin embargo, los servicios que vamos a utilizar incurren en pequeños cargos. En términos generales, estos no deberían exceder $ 1 / mes.

Usaremos una combinación de los siguientes servicios de AWS:

—S3

- Ruta53

- Administrador de certificados

- CloudFront

¡Entremos en ello!

Configure sus cubos S3

Primero, necesitará dos depósitos de S3 , ambos deben coincidir con su nombre de dominio personalizado con el segundo incluido el subdominio www.

Cubo 1:mywebsite.com

Cubo 2:www.mywebsite.com

El primer depósito (mywebsite.com) es el depósito principal de su sitio. Contiene todos sus archivos y activos para su sitio web estático.

A continuación, configuramos este depósito para alojamiento de sitios estáticos. Puede encontrar esto en la pestaña Propiedades del depósito, y mantendremos los valores predeterminados proporcionados aquí con el índice del sitio configurado en index.html.

También debemos hacer que este depósito sea de acceso público, ya que el navegador de un usuario deberá acceder a los archivos del depósito para poder representar el sitio web. Podemos hacer esto configurando una Política de depósito en la pestaña Permisos.

{ "Version": "2012-10-17", "Statement": [ { "Sid": "PublicReadGetObject", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "MY_BUCKET_ARN" } ]}

Esta es una política simple que solo permitirá el acceso público de lectura de los objetos en el depósito. Ahora, si se dirige al punto final definido en la configuración de alojamiento estático del depósito, debería ver su sitio web.

¡Progreso! Pero podemos hacerlo mejor que eso.

El segundo depósito (www.mywebsite.com) lo dejaremos vacío, pero lo configuraremos para redirigir a nuestro primer depósito utilizando HTTP como protocolo (lo haremos HTTPS más adelante).

¡Tus cubos ya están listos para funcionar!

Configurar dominios con Route53

Por lo tanto, su sitio web está en funcionamiento, pero solo se puede acceder a él a través del punto final del depósito y no su dominio personalizado. Cambiemos eso.

Dirígete a Route53 . Si ha registrado su dominio con Amazon Registrar, debería ver que se ha configurado una zona alojada para usted con dos conjuntos de registros. Uno para el servidor de nombres (NS) y otro para SOA.

Todo lo que tenemos que hacer es crear dos conjuntos de registros más para apuntar a los puntos finales del bucket de S3.

Para cada conjunto de registros:

- Tipo: A - Dirección IPv4

- Alias: si

- Destino de alias: el punto final del sitio web de S3 que coincide con lo que estableció para Nombre.

Ahora podemos ir a la URL personalizada ... ¡y listo!

Ya casi llegamos, pero falta una última cosa ...

Note: If your domain is registered with another domain registrar (not Amazon) you’ll need to follow some different steps to set this up. Usually you’ll need to add a CNAME record with a value of the main S3 buckets endpoint.

Troubleshooting:

If you deleted the hosted zone Amazon created when you first registered the domain (I’ve done this because hosted zones do incur some charges), you’ll need to create a new hosted zone from scratch.

  1. Select “Create Hosted Zone” and set the domain name, for example “mywebsite.com”
  2. This will generate some new record sets for types NS and SOA.
  3. Go into your registered domain and update the Name Servers values to those generated in the new NS record set.

Requesting a Certificate

Awesome, the site is now hosted using the custom url! However we can only access it via HTTP protocol.

We should always ensure our sites are secured using HTTPS protocol. This protects our site and users from malicious injection attacks and guarantees authenticity.

Head to Certificate Manager in AWS Console and request a new public certificate (this is free). You’ll be prompted to enter the domain names you wish to secure.

Before the certificate can be issued, Amazon needs to be able to verify that you own the specified domains.

You can choose from two verification methods: Email or DNS.

Email is generally simpler, but you’ll need to ensure you can access the email used to register the domain. Alternatively, if you used Amazon Registrar and Route53, you can select the DNS method. This requires you to add some specific record sets to the hosted zone, but this is mostly automated for you so it’s quite simple.

It can take a few minutes for the certificate to be issued after validation.

When its all done we can continue to the final step!

Configuring CloudFront

For the final step we are going to use CloudFront which allows us to use the new SSL certificate to serve the website with HTTPS. CloudFront also speeds up the distribution of web content by storing it at multiple edge locations and delivering from the closest edge location to a user.

We need two new web distributions, one for each S3 bucket. Head to CloudFront in the AWS Console and create the first web distribution.

There are lots of settings available to create a web distribution, but for the basics we only need to change five:

  1. Origin Domain Name: Set this to the S3 website endpoint for one of the buckets. Important: This field will give you some auto-complete options with your S3 bucket names. However, using these can cause issues with redirecting to the bucket endpoint. So instead use the bucket endpoint directly.
  2. Origin Id: This populated for you when you enter Origin Domain Name.
  3. Viewer Protocol Policy: Set to “Redirect HTTP to HTTPS”.
  4. Alternate Domain Names: This should match the name of the S3 bucket you’re pointing to. For example “mywebsite.com”.
  5. SSL Certificate: Select “Custom SSL Certificate” and select your new certificate from the dropdown.

Do this again for the second S3 bucket.

The distributions can take a while to spin up, so while we wait, let’s do the finishing steps.

Back in S3, go to your secondary bucket (www.mywebsite.com), in the Properties tab and under Static Website Hosting set the redirect protocol to HTTPS.

Finally, head back to Route53. We need to update the custom A records we created to now target the CloudFront distributions rather than the S3 buckets. For each record, change the Alias Target and select the CloudFront distribution available in the dropdown.

Note: Again, if you are using another DNS service you’ll need to go update the CNAME record from there to point to the CloudFront domain name.

And there you have it! Your beautiful website is now available at the custom domain and served with HTTPS!

Thanks for reading! I hope this guide was useful and enjoyable, I’d love to know if you found it helpful.