Nginx – How to setup nginx to redirect to https for certain host when behind an SSL termination load balancer

amazon-elbnginxredirectssl

Hello I have a web server (running nginx) in EC2 behind an ELB (load balancer) which terminates SSL connections.

If there is a request to www.domain.com it will go http to the ELB and be passed to http on the nginx server

If there is a request to secure.domain.com it should go to https to the ELB and be passed to http to the nginx server.

If a request comes in http://secure.domain.com I would like nginx to do a 301 redirect to https://secure.domain.com.

I can accomplish this by using the http_X_Forwarded_Proto header that is injected by the ELB. So something like

server {
  listen       80;
  server_name  secure.domain.com ;

  if ($http_X_Forwarded_Proto = http) {
    return       301 https://secure.domain.com$request_uri;
  }

  ....
}

The issue is that the "if ()" seems to get run across on the server blocks so a request for http://www.domain.com/foo (in a different server block) gets picked up by this if() and 301 to https://secure.domain.com/foo.

How can I configure nginx to just redirect secure.domains.com to https without effecting all my other vhosts?

Thank you

Best Answer

server {
   listen       80 default;
   server_name  domain.com ;
 ....
}

One option is to have a default server block.

Nginx Doc server_name

Second option is to have if loops to check the condition that the request is https and host is secure.domain.com.

if ($host == secure.domain.com){
    set $random_var 1;
}
if ($http_X_Forwarded_Proto == https ){
    set $random_var 10;
}
if ($random_var == 10){
    return       301 https://secure.domain.com$request_uri;
}

I personally prefer the first approach because I find it cleaner.