title: Nginx conditional rewrite
body: <p>I am trying to redirect domain1.com to domain2.com based on http/https. </p>
  
  <ul>
  <li>So a request to <a href="http://domain1.com" rel="nofollow">http://domain1.com</a> will go to <a href="http://domain2.com" rel="nofollow">http://domain2.com</a>. </li>
  <li>Request to <a href="https://domain1.com" rel="nofollow">https://domain1.com</a> goes to <a href="https://domain2.com" rel="nofollow">https://domain2.com</a></li>
  </ul>
  
  <p>My current Nginx vhost file setup as:</p>
  
  <pre><code>server {
      listen 80;
      listen 443 ssl;
  
      ssl_certificate /etc/nginx/xxx.crt;
      ssl_certificate_key /etc/nginx/xxx.key;
  
      server_name *.domain1.com;
      if ( $scheme = "https" ) {
          rewrite ^ https://domain2.com$request_uri? permanent;
      }
      rewrite ^ http://domain2.com$request_uri? permanent;
  }
  </code></pre>
  
  <p>However visiting <a href="https://domain1.com" rel="nofollow">https://domain1.com</a> just goes to <a href="http://domain2.com" rel="nofollow">http://domain2.com</a>. I can't seem to detect https. What am I doing wrong? Thanks. </p>
  
  <p><strong>EDIT:</strong>
  I have edited my vhost to the below but the same issue occurs.:</p>
  
  <pre><code>server {
      listen 80;
      listen 443 ssl;
  
      ssl_certificate /etc/nginx/xxx.crt;
      ssl_certificate_key /etc/nginx/xxx.key;
  
      server_name *.domain1.com domain1.com;
      return 301 $scheme://domain2.com$request_uri;
  }
  </code></pre>