published on in web tech

Conditional access using only nginx

Have you ever wanted to deploy a website to test that it works, without everyone else being able to see it?

If you are using a dynamic language or CMS for your webpage (PHP, Wordpress or Ruby on Rails) there are straightforward ways to accomplish this.

But what happens if you have a static webpage? Here I will present one solution using only a nginx config file to accomplish this.

# first we need to allow access to the soon.html
# and also a logo which is linked from the soon.html
# if your soon.html links more resources in this server
# you need to update the regex to match that also
location ~ /(soon\.html|images/logo_white.png) {
    try_files $uri =404;
}

# this is the secret way to get past the block
# it will set a magic cookie with a lifetime of 1 month
# and redirect back to the host  
location /iwanttobelieve {
  add_header Set-Cookie "iwantto=believe;Domain=$host;Path=/;Max-Age=2629746";
  return 302 $scheme://$host;
}

# this is the normal serve, but with a condition that everything
# everyone that does NOT have the magic cookie set will be served
# the content of soon.html
location / {
if ($http_cookie !~* "iwantto=believe") {rewrite ^ /soon.html last; }
	try_files $uri $url/ =404;
}

That it! Copy and paste the above into a server {} block. Make sure to take not of the order though to ensure you don’t have anything else before this which would take precedence. Then change all occurrences of soon.html if you use something else. And remember that the first match needs to match everything that this soon.html tries to reference, otherwise they will just get back the content of /soon.html for all other requests.

Note that if is a bit finicky in nginx, check their documentation for more details.