non www to www using AWS Elastic Load balancer and Nginx non www to www using AWS Elastic Load balancer and Nginx nginx nginx

non www to www using AWS Elastic Load balancer and Nginx


I had the same issue with the redirect (using same nginx conf code as shown here).

Then, I put my redirect configs as the last server{} block (at the end of my domain.com config file), and the ELB was able to find the instances again.

I have not looked more into it, but it seems that vhost processing is done in order, so when ELB hits the IP address of my servers, it lands on the first defined server{} block, which in my case was the redirect. Nginx throws a 301 return code, and ELB freaks out since its not 200.

Just a guess though.

So, my config (real vhost on top, redirect is last):

less /etc/nginx/sites-enabled/domain.com

server {    listen 80;    server_name domain.com;    .....}server {    listen       80;    server_name  www.domain.com;    return       301 http://domain.com$request_uri;}


I'm not familiar with Amazon ELB, but perhaps I can help with the nginx part.

For your scenario, I normally use two server blocks in nginx. One to handle the rewrite/ redirect (example.com), and the other to handle the regular site (www.example.com). Both blocks can be in the same file.

# for redirecting only...server {    listen 80;    server_name example.com;    # re-written to www...    location / {       rewrite ^(.*)$ $scheme://www.example.com$1 permanent;    }}# regular web site config here...server {    listen 80;    server_name www.example.com;    root /home/ubuntu/apps/st/public;    passenger_enabled on;    ...}


Old question, but since it comes up in searches.

Redirecting to www (or any other host) is now possible with AWS application load balancers. This could be more convenient to manage than using nginx config.

https://docs.aws.amazon.com/elasticloadbalancing/latest/application/listener-update-rules.html