Today, I needed to take a website offline, because it wasn't ready to be shown to the world yet. What I wanted was to show a "we're under maintenance" screen, when the user visits the site. It should also automatically redirect any traffic to that screen, so if the user tried to visit
/subpage, they would be redirected to
/maintenance. Here's how I did it with my Gatsby page hosted on Netlify.
Create a branch in my repository where I will add the maintenance screen.
I called it
git checkout -b maintenance
Make Netlify deploy this newly created branch. By default, Netlify only deploys your
production branch. That's usually
master, or it was in my case. To change this, I go to
Settings > Build & Deploy > Deploy contexts, click edit and choose
Let me add individual branches under
Branch deploys. Then I add my branch name
Add the screen to my Gatsby project.
I did this by creating a new folder called
pages and added an
index.tsx and a
styles.scss. This page pretty much just says "Here's going to be the new home of this project", has links to social media and basic styling. Gatsby will automatically create a route for this, so when I visit
page-name.com/maintenance, I get the screen.
Add the redirect.
One way of getting Netlify to do the redirect I want is to add a file called
_redirects to the directory that Netlify uses to serve the website and put the redirects in there. In the case of Gatsby which has its own build process, it's not trivial to get the file into the
public folder, where it needs to be.
To get Gatsby to put the file there, I created a folder called
static (on the root of my project) and put the file in there. Gatsby takes all these files and puts them into
public during the build process.
The content of the file is very simple:
/* /maintenance 301!
These changes are pushed to the
Deploy the published branch.
I open the deployment status page with the deploy log. There, I can find a button that says "publish deploy".
This will make the branch
maintenance the base of my production site. Now, when I visit the main URL e.g.
https://page-name.com, I see the maintenance screen.
To undo this, I can just go to one of the older deploys and click "publish deploy" there. This will bring back the master branch to the production site. I can obviously also just make a new commit to the master branch, go into that deploy log and press "publish deploy" there.
- My site is connected to a Contentful instance. When content is updated, a webhook is triggered and a new deployment starts. In Netlify, by default, auto-publishing for the
masterbranch (or whatever you've set as your production branch) is enabled. This will, after having built the site, set the production site to the
masterbranch again, effectively undoing Step 5. To stop Netlify from doing this, just press the "Stop auto publishing" button in the deploys list page in the Netlify UI.