Search code examples
urlnext.jsroutespathnext-router

NextJS: 404 when coming from browser to subpath


I deployed my NextJS app as a static website on my own server and it's working well. Except that if I try to access a page that is not the main page through typing the url in the browser, I get a 404. (When I come from the navigation within the app, it's working though!)

As far as I know, to create the paths I need, I just create a .js in the pages folder. This doesn't seem to be enough though?

Does it have anything to do with the process.env.BASE_URL? Or with any router?

Here's one of my files in the pages folder:

import { Fragment, Suspense } from 'react';
import dynamic from 'next/dynamic';
import Loading from '../components/shared/Loading';
import SeoHead from '../components/SeoHead';

import myIMG from '../images/header_myimg.jpg';

const ThemeContent = dynamic(() => import('../components/ThemeContent'));
const ContentXYZ = dynamic(() => import('../components/ContentXYZ'));
const Contact = dynamic(() => import('../components/Contact'));

export default function Sucht(){

    return (
        <Fragment>
            <SeoHead
                title="xyz"
                description="xyz"
                url="/my-url"
            />
            <Suspense fallback={<Loading/>}>
                <ThemeContent 
                    titleColor="darkblue"
                    image={myIMG}
                    imgAlt="xyz"
                    title="xyz"
                    subtitle="xyz"
                    text={<ContentXYZ/>}
                />
                <Contact/>
            </Suspense>
        </Fragment>
    );
}

And here is my next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
    reactStrictMode: false,
    env:{
        BASE_URL: process.env.BASE_URL
    },
    experimental: {
        images: {
            layoutRaw: true,
            deviceSizes: [320, 380, 500, 750, 1000, 1200, 1450],
            formats: ['image/webp'],
            loader: "custom"
        }
    }
}

module.exports = nextConfig

Would you need anything else? I'm sure this is something easy... I really appreciate your help!

(I saw that this question has been asked already but it seems to me they didn't have a static website and didn't host it on their own server. So the answers didn't really fit to my problem?)


Solution

  • I found a solution! I put a .htaccess in the public-folder! I wrote this in the file:

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([^\.]+)$ $1.html [NC,L]