non www to www using AWS Elastic Load balancer and

2019-04-12 07:08发布

问题:

I have an app running on example.com and now I wanna redirect all the traffic to the www.example.com since we are collaborating with Akamai's CDN for your website. My domain is parked in Route53, added the CNAME of Elastic Load Balancer's CNAME to pointing to *.example.com and I am running nginx web server with the following configuration. If I use this configuration ELB is throwing the instance out, now domain.com works fine and www.domain.com fine, but redirecting is not happening.

server {
        listen 80;
        server_name example.com;
#       rewrite ^    http://www.example.com$request_uri? permanent;
        root /home/ubuntu/apps/st/public;
        passenger_enabled on;
}

but I am not able to achieve the redirect.

Also tried to add the PTR whose value is the cname of the load balancer.

Tried to change the nginx configuration, as you can see

rewrite ^ http://www.example.com$request_uri? permanent;

even that is not working.

As soon as I add the above line, the app instance goes and ELB throws out of the stack.

What is the solution, I have been trying to achieve this since 3-4 days, its become a night mare now, kindly help me up. I have also put posts and threads in aws forums, nothing is helping as such.

回答1:

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;
}


回答2:

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;
    ...
}