Question

Host blog as a subdirectory

Hello,

I have a static NextJS blog that I would like to host on the subdirectory of my main site. Like this: example.com/blog.

I’ve tried uploading the files and creating a location block like this:

location /blog {
     root /var/www;
}
// The inital blog page loads but the dynamic routes don't

However this doesn’t work when I try to visit something like exmaple.com/blog/post/post-title-here.

How could I configure this, I’m pretty new to managing servers so apologies if this is an easy question.


Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Accepted Answer

Hi there,

With Next.js, you need to start your node service on a specific port like 3000 for example with npm run. And then you could use Nginx as a reverse proxy to that port with the following configuration:

location /blog  {
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    }

Here is a good article that shows how to set up a server for Node.js application:

https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-20-04

Let me know how this goes. Regards, Bobby

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

Hi @evalo01,

You’ve almost got it!

You can try and edit it to look like so:

  location /blog {
    alias  /var/www;
    index  index.html index.htm;
    try_files $uri $uri/ /blog;
  }

That should be enough. That’s at least for projects where you can use Nginx’s port.

In the case of NextJS, your application is running with NodeJS which runs on specific port. You can take @bobbyiliev’s advice and set a reverse proxy location in your Nginx configuration:

location /blog  {
            proxy_pass http://localhost:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
    }