9

I made a next.js export into the out folder.

Folder structure is:

  • out
    • index.html
    • terms.html
    • privacy.html

I set up nginx to serve files from this folder:

server {
    root /var/www/myproject/out;
    index index.html index.htm index.nginx-debian.html;

    server_name myproject.com;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

The main page (index) opens fine. Navigation from within the app to urls like myproject.com/privacy works fine. The problem is if I try to open these links directly, it will serve the main page (index) instead of the actual pages, since those urls don't exist in the folder. The only way to open the privacy page directly is adding the html extension to the url: myproject.com/privacy.html.

How to configure nginx to serve the actual page myproject.com/privacy.html when someone enters the myproject.com/privacy url?

3
  • 4
    in try_files include $uri.html
    – Nayan
    Commented May 27, 2022 at 13:04
  • 1
    @Nayan bless you my friend, it works as expected. Do you want to create a proper answer so I can accept it?
    – orszaczky
    Commented May 27, 2022 at 13:52
  • Sure. Added answer.
    – Nayan
    Commented May 27, 2022 at 14:00

3 Answers 3

17

Issue is in try_files.

As current configuration includes:

  • / (which default route to index.html at root path)
  • index.html
  • /index.html
  • test/*.html

To access pages route path name without extension i.e., /privacy that format should be included in try_files insdie location /

Try this:

try_files $uri $uri.html /$uri /index.html
8

I needed a 2nd location block because of the way NextJS does ids in the url. NextJS will have files like [id].html or whatever.

    location / {
        try_files $uri $uri.html /$uri /index.html;
    }

    location ~* /(.*)/(\d+)$ {
        try_files $1/[id].html /$1/[id].html /index.html;
    }

So I needed the 2nd block to catch urls of the form /whatever/etc/5 and redirect nginx to /whatever/etc/[id].html

3
  • Does not work for me Commented Aug 2, 2023 at 17:51
  • @PatrickWaweru i may have dropped a slash in the regex before the digits. Edited. Commented Aug 2, 2023 at 18:07
  • I will try it and give you feedback Commented Aug 7, 2023 at 14:28
0

I tried this configuration and it works like charm.

server_name example.com;

root /var/www/example.com/;
index index.html;

location / {
    try_files $uri $uri.html /$uri $uri/ /404.html =404;
}

location ~ ^/[^/]+\.html$ {
    try_files $uri $uri/ /index.html;
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.