Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I put NextJS in subfolder like localhost/next?

I try to build static files from Next.js, but I want to put it in subfolder of shared host or my localhost like localhost/nextweb.

I tried to find some example, but I found only putting NextJS in root.

My next.config.js looks like

const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
const { ANALYZE } = process.env
module.exports = {
  webpack: function (config) {
    if (ANALYZE) {
      config.plugins.push(new BundleAnalyzerPlugin({
        analyzerMode: 'server',
        analyzerPort: 8888,
        openAnalyzer: true
      }))
    }

    return config
  },
  exportPathMap: () => ({
    "/": { page: "/" },
    "/about": { page: "/about" }
  }),
  assetPrefix: 'http://localhost/nextweb/'
}

When I open some page, it's working, but when I click a link it shows me an network request error:

http://localhost/nextweb/_next/a5126d9c-d338-4eee-86ff-f4e6e7dbafa6/page/nextweb/about/index.js 404 not found.

but real file is contain in .../page/about/index.js not /page/nextweb/about/index.js

What should I do about this?

like image 548
Nuttawut Anek Avatar asked Sep 28 '17 17:09

Nuttawut Anek


Video Answer


2 Answers

To deploy a Next.js application under a sub-path of a domain you can use the basePath config option.
basePath allows you to set a path prefix for the application. For example, to use /docs instead of / (the default), open next.config.js and add the basePath config:

module.exports = {
  basePath: '/docs',
}

Source: Base Path

like image 162
Omar Avatar answered Nov 02 '22 23:11

Omar


 location /SUBPATHNAME/_next/ {
      alias /PROJECTROOT/.next/;
      autoindex on;
      expires 30d;
      access_log on;
      location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires max;
        log_not_found off;
      }
    }
    location /SUBPATH/ {
      rewrite ^/SUBPATH(/.*)$ $1 break;
      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;
    }

So what is happening there is next is trying to find media and static files in the root directory thus you need to explicitly provide location where nginx will grab these media files

also in the node.config.js

 const isProd = process.env.NODE_ENV === 'production'
 module.exports= ({assetPrefix: isProd ? 'https://myproduction' : ''})

NOTE: The above code block might not be really optimized this is what i came up with you can change according to your usecase

like image 40
Gopherine Avatar answered Nov 02 '22 23:11

Gopherine