Skip to content

Instantly share code, notes, and snippets.

@rutcreate
Last active April 28, 2022 06:29
Show Gist options
  • Save rutcreate/f9aea4d3ed0eae3b7e7a5d42cb3fc688 to your computer and use it in GitHub Desktop.
Save rutcreate/f9aea4d3ed0eae3b7e7a5d42cb3fc688 to your computer and use it in GitHub Desktop.
Generate NGINX locations for Nextjs pages
const fs = require('fs')
const path = require('path')
const nextConfig = require('../next.config')
// Create pages directory.
// NOTE: if you have different location, please change.
const pageDir = path.join(__dirname, '../src/pages')
// Determine trailing slash configuration.
const isTrailingSlash = nextConfig.trailingSlash === undefined
? false
: nextConfig.trailingSlash
// Get files recursively with full
const getFiles = (dir, files) => {
files = files || [];
for (const fileName of fs.readdirSync(dir)){
// Ignore file start with _
if (fileName.startsWith('_')) {
continue
}
const name = dir + '/' + fileName;
// If it is directory, get files inside it.
if (fs.statSync(name).isDirectory()){
getFiles(name, files);
}
// Put file info list.
else {
files.push(name.replace(pageDir, ''));
}
}
return files;
}
const locations = []
for (const filePath of getFiles(pageDir)) {
// Parse [dynamic] params
// [xxx] => ([a-zA-Z0-9\-]+)
let uri = filePath.replace('.tsx', '').replace(/\[\w+\]/g, '([a-zA-Z0-9\-]+)')
// Replace tsx to html.
let location = filePath.replace('.tsx', '.html')
// If trailing slash config is disabled,
// remove "index" from URI and location.
if (!isTrailingSlash && uri.endsWith('/index')) {
// Turn uri /xxx/index to /xxx
uri = uri.substring(0, uri.length - '/index'.length)
// Turn location /xxx/index.html to /xxx.html
location = location.substring(0, location.length - '/index.html'.length) + '.html'
}
locations.push(`location ~ ^${uri}/?$ {`)
locations.push(`\ttry_files ${location} =404;`)
locations.push(`}\n`)
}
// Write file.
fs.writeFileSync(
path.join(__dirname, '../nginx/location.locations'),
locations.join('\n')
)
server {
server_name your-domain.com;
listen 80;
root /your/dir/nextjs/export/out;
# Support only /index.html and other assets in /public directory
location / {
try_files $uri $uri/ =404;
}
include /your/generated/above/nginx/location.locations;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment