tutorial pricing elastic ec2 aws amazon-web-services nginx amazon-ec2 elastic-beanstalk

amazon web services - pricing - ¿Cómo hacer que Elastic Beanstalk el servidor proxy respaldado por nginx redireccione automáticamente de HTTP a HTTPS?



elastic beanstalk docker (7)

Estoy ejecutando el entorno ''Ruby2 Puma'' en AWS Elastic Beanstalk que puede tener una configuración ligeramente diferente a la anterior. En mi entorno, necesitaba usar ''escuchar 80'' en lugar de ''escuchar 8080''.

sslredirect.config según la respuesta de elloworld111 :

files: "/etc/nginx/conf.d/000_my_config.conf": mode: "000755" owner: root owner: root content: | server { listen 80; return 301 https://$host$request_uri; }

Tengo un sitio con motor Node.js que estoy ejecutando en Amazon Elastic Beanstalk.

Mi aplicación Node.js escucha en el puerto 8080, y estoy usando la configuración del equilibrador de carga elástico nginx con mi aplicación EB, escuchando en el puerto 80 y 443 para HTTP y HTTPS.

Sin embargo, solo quiero aceptar el tráfico en mi aplicación que ha llegado a través de HTTPS.

Podría arreglar algo en la aplicación para tratar con esto, pero estoy interesado en una forma de hacer que el equilibrador de carga redirija todas las solicitudes HTTP a mi sitio a través de HTTPS.


Estoy trabajando con Elastic Beanstalk y Docker, así que he tomado una ruta ligeramente diferente para que todo funcione, pero muy inspirado por la respuesta aceptada. Este script inyecta la configuración requerida en /etc/nginx/sites-available/elasticbeanstalk-nginx-docker-proxy.conf. (Si alguien tiene una solución más elegante me encantaría verla)

Esta secuencia de comandos también permite que Beanstalk Healthcheck llegue al punto final de mi chequeo de salud (en mi caso, api / healthcheck). Es mejor permitir que LoadBalancer acceda a la aplicación, en lugar de finalizar en Nginx.

files: "/tmp/45_nginx_https_rw.sh": owner: root group: root mode: "000755" content: | #! /bin/bash CONFIGURED=`grep -c "return 301 https" /etc/nginx/sites-available/elasticbeanstalk-nginx-docker-proxy.conf` if [ $CONFIGURED = 0 ] then sed -i "/access.log;/a / / / / / / / / location /api/health-check { proxy_pass http://docker; }" /etc/nginx/sites-available/elasticbeanstalk-nginx-docker-proxy.conf sed -i "/proxy_add_x_forwarded_for;/a / / / / / / / / / / / / if (/$http_x_forwarded_proto != ''https'') { return 301 https:///$host/$request_uri; }" /etc/nginx/sites-available/elasticbeanstalk-nginx-docker-proxy.conf logger -t nginx_rw "https rewrite rules added" exit 0 else logger -t nginx_rw "https rewrite rules already set" exit 0 fi container_commands: 00_run_script: command: /tmp/45_nginx_https_rw.sh


La respuesta aceptada ya no funcionó para mí. El puerto predeterminado era diferente. También la ubicación del archivo de configuración ha cambiado. Estoy configurando una aplicación Ruby On Rails con Puma.

Hablé con el soporte pago, lo descubrimos simplemente ejecutando los comandos manualmente en la instancia en ejecución. Entonces pude descifrar la siguiente solución. Simplemente iniciando sesión y reiniciando nginx las cosas funcionaron.

files: "/tmp/45_nginx_https_rw.sh": owner: root group: root mode: "000644" content: | #! /bin/bash CONFIGURED=`grep -c "return 301 https" /opt/elasticbeanstalk/support/conf/webapp_healthd.conf` if [ $CONFIGURED = 0 ] then sed -i ''/listen 80;/a / if ($http_x_forwarded_proto = "http") { return 301 https://$host$request_uri; }/n'' /opt/elasticbeanstalk/support/conf/webapp_healthd.conf logger -t nginx_rw "https rewrite rules added" exit 0 else logger -t nginx_rw "https rewrite rules already set" exit 0 fi container_commands: 00_appdeploy_rewrite_hook: command: cp -v /tmp/45_nginx_https_rw.sh /opt/elasticbeanstalk/hooks/appdeploy/enact 01_configdeploy_rewrite_hook: command: cp -v /tmp/45_nginx_https_rw.sh /opt/elasticbeanstalk/hooks/configdeploy/enact 02_rewrite_hook_perms: command: chmod 755 /opt/elasticbeanstalk/hooks/appdeploy/enact/45_nginx_https_rw.sh /opt/elasticbeanstalk/hooks/configdeploy/enact/45_nginx_https_rw.sh 03_rewrite_hook_ownership: command: chown root:users /opt/elasticbeanstalk/hooks/appdeploy/enact/45_nginx_https_rw.sh /opt/elasticbeanstalk/hooks/configdeploy/enact/45_nginx_https_rw.sh

Observe cómo cambié el número de puerto y la ubicación del archivo de configuración.


Pude hacer que esto funcionara de una manera diferente. Cambié mi balanceador de carga para reenviar el tráfico del puerto 80 al puerto 8082, y cambié las reglas del firewall (entrantes en la instancia, salientes en el firewall) para permitir eso. Y luego agregué este archivo en .ebextensions:

files: "/etc/nginx/conf.d/50-atd-hotel-http-redirect.conf": mode: "000644" owner: root group: root content: | server { listen 8082; return 301 --WHATEVER DESTINATION YOU WANT--; }


Pude hacer que funcionara con una solución ligeramente más simple.

Tenga en cuenta que se trata de una instancia SINGLE desplegada de judías elásticas, no cargadas balenced.

Esta fue mi ebextension, agregué.

files: "/etc/nginx/conf.d/000_my_config.conf": mode: "000755" owner: root owner: root content: | server { listen 8080; return 301 https://$host$request_uri; }


Puede manejar la redirección a través de su aplicación Node.js.

Amazon envía el encabezado X-Forwarded-Proto que es igual a http cuando el cliente se ha conectado de forma insegura.

El siguiente middleware debe insertarse justo después de inicializar Express y antes de definir sus rutas para redirigir automáticamente al cliente al punto final HTTPS correspondiente:

// Redirect to HTTPS app.use(function (req, res, next) { // Insecure request? if (req.get(''x-forwarded-proto'') == ''http'') { // Redirect to https:// return res.redirect(''https://'' + req.get(''host'') + req.url); } next(); });


Después de varios comienzos falsos con ideas del soporte pagado de Amazon, al final terminaron. La forma de hacer que esto funcione es configurar su entorno para que responda tanto al puerto 80 como al 443. Luego, cree una carpeta en su carpeta principal de la aplicación Node.js llamada .ebextensions , y coloque un archivo llamado 00_nginx_https_rw.config allí, con este texto como el contenido:

files: "/tmp/45_nginx_https_rw.sh": owner: root group: root mode: "000644" content: | #! /bin/bash CONFIGURED=`grep -c "return 301 https" /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf` if [ $CONFIGURED = 0 ] then sed -i ''/listen 8080;/a / if ($http_x_forwarded_proto = "http") { return 301 https://$host$request_uri; }/n'' /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf logger -t nginx_rw "https rewrite rules added" exit 0 else logger -t nginx_rw "https rewrite rules already set" exit 0 fi container_commands: 00_appdeploy_rewrite_hook: command: cp -v /tmp/45_nginx_https_rw.sh /opt/elasticbeanstalk/hooks/appdeploy/enact 01_configdeploy_rewrite_hook: command: cp -v /tmp/45_nginx_https_rw.sh /opt/elasticbeanstalk/hooks/configdeploy/enact 02_rewrite_hook_perms: command: chmod 755 /opt/elasticbeanstalk/hooks/appdeploy/enact/45_nginx_https_rw.sh /opt/elasticbeanstalk/hooks/configdeploy/enact/45_nginx_https_rw.sh 03_rewrite_hook_ownership: command: chown root:users /opt/elasticbeanstalk/hooks/appdeploy/enact/45_nginx_https_rw.sh /opt/elasticbeanstalk/hooks/configdeploy/enact/45_nginx_https_rw.sh

El equipo de soporte de Amazon explicó: Esta configuración crea un enlace de despliegue que agregará las reglas de reescritura a /etc/nginx/conf.d/00_elastic_beanstalk_proxy.conf.

(Anteriormente me habían ofrecido .config''s que copiaba archivos separados en /etc/nginx/conf.d, pero esos no tenían ningún efecto, o peor, parecían sobrescribir o tener prioridad sobre la configuración predeterminada de nginx, por algún motivo).

Si alguna vez desea deshacer esto, es decir, para eliminar los ganchos, necesita eliminar esta extensión de ebextension y emitir un comando para eliminar los archivos que crea. Puede hacerlo manualmente o mediante comandos ebextensions que instaló temporalmente:

/opt/elasticbeanstalk/hooks/appdeploy/enact/45_nginx_https_rw.sh /opt/elasticbeanstalk/hooks/configdeploy/enact/45_nginx_https_rw.sh

No he intentado esto, pero presumiblemente algo así funcionaría para eliminarlos y deshacer este cambio:

container_commands: 00_undochange: command: rm /opt/elasticbeanstalk/hooks/appdeploy/enact/45_nginx_https_rw.sh 01_undochange: command: rm /opt/elasticbeanstalk/hooks/configdeploy/enact/45_nginx_https_rw.sh

Espero que esto pueda ayudar a alguien más en el futuro.