Multiple conditions rewrite in NGINX

If you have ever encountered programming more seriously than getting the message “Hello world!” on screen, you know what conditions (cases) are. But, let me remind you: sometimes you must tell a code what (not) to do in certain situations. Code is not executing always in same circumstances, right? That’s why we have to predict them and prepare code onward. If you are still reading then there is no reason for introducing you to programming anymore, so let me introduce you to NGINX’s rewrites.

Let’s get to the point

If you ever worked with NGINX-based servers, then you already know that you cannot make rewrite with multiple conditions and that NGINX doesn’t consider .htaccess file.

This is a trick I’ve used many times and I’d like to share it. Imagine that we have one NGINX server with 1 Magento webshop that has 4 stores with own domains. Client decided to increase security by buying SSL certificates and you want all traffic to go through it. Client prepared only 3 SSL certificates. Hmmm, 3 SSL certificates? Didn’t we imagine that we have 4 domains? No problem, the following trick will help!

Let’s make rewrite for 3 domains with the following logic: if visitor comes from HTTP, he should be redirected to HTTPS but not for one domain that doesn’t have SSL certificate, because you don’t want the fourth store being redirected to HTTPS when you have no SSL certificate for it. Hope you understand Regex 🙂

if ($server_port = 80) {
   set $cond A;    
}
if ($http_host ~ ^(www\.)?(example1.com|example2.com|example3.com)) {
   set $cond "${cond}B";
}
if ($cond = AB) {
   rewrite ^ https://$host$request_uri permanent;
}

Of course, the second condition could be set differently: instead of checking if $http_host is any of listed, we could test if $http_host is not example4.com. That’s it! Looks like old school – but it works!

The author of the text is Nebojša Stojilković, Magento web developer at Younify.

Discover Hyvä, the Magento game-changer that will transform your webshop. Learn more here.