React Production Build shows 404 on page refresh

2019-07-27 05:10发布

问题:

I have a ReactJS application which works very well on development environment. I am using webpack. When I run yarn build and I drop my files on my server, everything runs fine. but if I click refresh on the browser, I get a 404.

My server uses Apache. I have tried htaccess, I have done historyFallBackApi. None of them seem to solve my problem

Here is my .htaccess

RewriteBase /
RewriteCond %{REQUEST_URI} !^/(assets/?|$)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

Here is my webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin');

const modeConfig = env => require(`./config/webpack.${env}`)(env);
const webpackMerge = require('webpack-merge');
const path = require('path');


module.exports = (
    { mode } = { mode: 'development', presets: [] },
) =>
// console.log(`mode: ${mode}`);
    webpackMerge(
        {
            mode,
            entry: './src/index.js',
            resolve: {
                extensions: ['.js', '.jsx', '.css', 'scss'],
            },
            devServer: {
                historyApiFallback: { index: '/' },
                contentBase: './',
                open: true,
                port: 4100,
            },
            module: {
                rules: [
                    {
                        test: /\.(png|jpg|jpeg|gif|ico)$/,
                        exclude: /node_modules/,
                        loader: 'url-loader?limit=8192',
                    },
                    {
                        test: /\.(js|jsx|mjs)$/,
                        exclude: /node_modules/,
                        use: 'babel-loader',
                    },
                    {
                        test: /\.(woff|woff2|eot|ttf)$/,
                        loader: 'url-loader?limit=100000',
                    },
                    {
                        test: /\.svg$/,
                        loader: 'svg-inline-loader?classPrefix',
                    },
                ],
            },

            output: {
                publicPath: '/',
                path: path.resolve(__dirname, 'build'),
                filename: 'bundle.js',
            },
            plugins: [
                new HtmlWebpackPlugin({
                    template: './public/index.html',
                }),

                // new FaviconsWebpackPlugin({ logo: "./public/image.png" })
            ],
        },
        modeConfig(mode),
    );

Here is my route



function App() {
    return (
        <Router history={history}>
            <Switch>
                <Route exact path="/" component={LoginComponent} />
                <Route path="/reset-password" component={ResetPassword} />
                <Route path="/dashboard" component={Dashboard} />
                <Route path="/cards" component={CardsList} />
                <Route path="/view-card" component={ViewCard} />
                <Route path="/transactions" component={Transfer} />
                <Route path="/users" component={UsersList} />
                <Route path="/edit-user" component={EditUser} />
            </Switch>
        </Router>
    );
}

export default App;

Here is my custom history

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

export default history;

I keep getting 404 on Page refresh on the server.

回答1:

I would update your .htaccess file to be like this. The problem is likely that what you are currently using as your .htaccess file does not redirect 404 errors to index.html:

RewriteEngine On  
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]

RewriteRule ^ /index.html [L]

I would also add a custom 404 page. To do that, you need to create a new component and add another route to your switch. The route shouldn't have a path and should be the last route of the switch.

<Route component={NotFoundComponent} />