Nuttawut Anek
Nuttawut Anek

Reputation: 443

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?

Upvotes: 10

Views: 16611

Answers (3)

Omar
Omar

Reputation: 7641

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

Upvotes: 18

Trees4theForest
Trees4theForest

Reputation: 1396

Not natively. Not at this time (still in 2019). Here is the relevant thread:

https://github.com/vercel/next.js/issues/4998

There is an experimental feature in the works:

https://github.com/vercel/next.js/pull/9872

Upvotes: 0

Gopherine
Gopherine

Reputation: 1111

 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

Upvotes: 2

Related Questions