Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.