如何从URL子目录而非根目录部署Heroku应用?
Got it, let's walk through how to set up your Nuxt SSR app on Heroku so it only serves content at /homepage (with the root path returning a 404), and gets that custom path showing up in your deployment logs.
Step 1: Configure Nuxt's Base Route
First, tell Nuxt that your app lives under /homepage by updating your nuxt.config.js:
export default { // Set the base URL for all routes router: { base: '/homepage' }, // Add a hook to catch root path requests and return 404 hooks: { 'router:extendRoutes'(routes, resolve) { // Add a route for the root that loads your 404 page routes.push({ path: '/', component: resolve(__dirname, 'pages/404.vue') }) } }, // Ensure the server listens on the correct Heroku port/host server: { port: process.env.PORT || 3000, host: '0.0.0.0' } }
Make sure you have a pages/404.vue component created for the 404 page content.
Step 2: Handle Root Path at the Server Level (Optional but Recommended)
If you're using a custom Node/Express server (instead of Nuxt's default), add a direct handler for the root path to return a 404 immediately, before Nuxt processes it. Here's an example server.js:
const express = require('express') const { loadNuxt, build } = require('nuxt') const app = express() const isDev = process.env.NODE_ENV !== 'production' // Directly return 404 for root path requests app.get('/', (req, res) => { res.status(404).send('<h1>404 Not Found</h1>') }) async function start() { const nuxt = await loadNuxt(isDev ? 'dev' : 'start') const host = process.env.HOST || '0.0.0.0' const port = process.env.PORT || 3000 // Let Nuxt handle all other routes (under /homepage) app.use(nuxt.render) if (isDev) await build(nuxt) app.listen(port, host) console.log(`Running on http://${host}:${port}`) } start()
If you use this custom server, update your Procfile to point to it:
web: node server.js
If you stick with Nuxt's default server, your Procfile can just be:
web: nuxt start
Step 3: Customize Heroku Deployment Log Message
Heroku's default log shows the root app URL, but we can add a post-deploy script to output the /homepage URL instead. Update your package.json scripts:
{ "scripts": { "dev": "nuxt", "build": "nuxt build", "start": "nuxt start", "postdeploy": "echo \"https://$(heroku apps:info -s | grep web_url | cut -d= -f2 | tr -d '\n')homepage deployed to Heroku\"" } }
This script grabs your app's root URL from Heroku's environment, appends /homepage, and prints the custom message to your deployment logs.
Testing Locally First
Before pushing to Heroku, test locally:
- Run
npm run build && npm run start - Visit
http://localhost:3000/– you should see your 404 page - Visit
http://localhost:3000/homepage– your app should load normally
Once everything works locally, push to Heroku and check the logs – you'll see your custom deployment message, and the root path will return 404 as expected.
内容的提问来源于stack exchange,提问作者robskrob

