Subpath with Nginx and Gatsby

Abhinav Rai
2 min readOct 20, 2020

Use Case

We have our website hosted on https://growpad.io and we want to add blog. Both website and blogs are made with Gatsby but with different themes and hence they are different packages to be served.

https://blogs.growpad.io Vs https://growpad.io/blogs

Winner: https://growpad.io/blogs for SEO purposes

So, on our nginx if a request that starts with /blogs come, that needs to be served to blogs gatsby build while the other ones have to be served by website gatsby build.

How Nginx works?

There is location block in nginx which directs what to do when a specific request matches the location. Whether to serve file or proxy it to a specific server running.

Now, while serving the file there is something called as root and alias.

root -> adds matched location path automatically to file location

alias -> doesn’t add matched location path automatically to file location

Short + Great answer on the same: https://stackoverflow.com/questions/10631933/nginx-static-file-serving-confusion-with-root-alias

Gatsby Path Prefix

We need to add a path prefix “blogs” to gatsby blogs.

More on this here: https://www.gatsbyjs.com/docs/path-prefix/

Build the gatsby project by adding the path prefix “blogs”. So when you do gatsby build --prefix-paths && gatsby serve --prefix-paths you will see the localhost:9000/blogs up and running. So all js, css, images, etc calls go like localhost:9000/blogs/{something.js|css|jpeg} instead of root.

Final Nginx configuration

location / {
root /var/www/growpad.io/html;
index index.html;
}
location /blogs/ {
alias /var/www/blogs/html/;
index index.html;
}

See the root and alias.

Go through the blog and link again if you didn’t understand. You just need to understand

  1. Which location is served based on the route
  2. What is alias and root and the different between them

--

--

Abhinav Rai

Buliding Engagebud | Guitarist | Traveller | Entrepreneur