Question

Host blog as a subdirectory

Posted June 17, 2021 126 views
NginxNext.js

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.

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.

×
Submit an Answer
2 answers

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

by Lisa Tagliaferri
by Kathleen Juell
Node.js is an open-source JavaScript runtime environment for building server-side and networking applications. The platform runs on Linux, macOS, FreeBSD, and Windows. Though you can run Node.js applications at the command line, this tutorial will…

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;
    }