Fastly - Basic authentication for a single page

Goal

Protect a website page or pages at the edge. Users enter a username and password combination to access pages protected by basic authentication.

Steps

  1. Go to Stores > Configuration > Advanced > System > Full Page Cache > Fastly Configuration > Custom VCL Snippets
  2. Generate a login/password paid by running the following command in terminal:
    echo -n "login:password" | base64
    
    In this example, the result of execution will be bG9naW46cGFzc3dvcmQ=.
  3. Add the following RECV VCL snippet:
    if ( req.method != "FASTLYPURGE" &&
     ! req.http.Authorization ~ "Basic bG9naW46cGFzc3dvcmQ=" &&
     req.url.path ~ "%page URI or regexp%") {
     error 772;
    }
    
  4. Add the following ERROR VCL snippet:
    if (obj.status == 772) {
     set obj.http.Content-Type = "text/html; charset=utf-8";
     set obj.http.WWW-Authenticate = "Basic realm=Secured";
     set obj.status = 401;
     synthetic {"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
     "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
     <HTML>
     <HEAD>
     <TITLE>Error</TITLE>
     <META HTTP-EQUIV='Content-Type' CONTENT='text/html;'>
     </HEAD>
     <BODY><H1>401 Unauthorized</H1></BODY>
     </HTML>
     "};
     return (deliver);
    }
    
  5. Upload VCL to Fastly.