skip to Main Content

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?

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search