React Router路由在Nginx create-react-app上不起作用 [英] React Router routes not working on nginx create-react-app

查看:68
本文介绍了React Router路由在Nginx create-react-app上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用"react-router-dom":"^ 4.2.2" .

如果我在 localhost:3000/second 上进行测试,则可以完美运行.

If I test on localhost:3000/second it works perfectly.

当我使用nginx将其上传到ubuntu服务器上并尝试 www.website.com 时,它可以工作.当我尝试使用 www.website.com/second 时,它提示我 404未找到.我正在使用 create-react-app .

When I upload this on ubuntu server with nginx and I try www.website.com, it works . When I try to use www.website.com/second it gives me 404 not found. I'm using create-react-app.

app.js

class TestRoutes extends React.Component{
    constructor(props){
        super(props);
    }
    render(){
        return(<React.Fragment>
            <BrowserRouter>
                <Switch>
                    <Route exact path='/' component={MainPage}/>
                    <Route path='/second' component={SecondPage}/>
                    <Route path='/third' component={ThirdPage}/>
                </Switch>
            </BrowserRouter>
                </React.Fragment>);
    }
}

ReactDOM.render(<TestRoutes/>, document.getElementById("root"));

/etc/nginx/sites-available/default 这是服务器上的配置文件

/etc/nginx/sites-available/default Here's the configuration file from the server

server {
        listen 443 ssl;

    root /var/www/reactcamera/build;

    # Add index.php to the list if you are using PHP
    index index.html index.htm index.nginx-debian.html;
    server_name website.com www.website.com;
    ssl_certificate /etc/letsencrypt/live/website.com/fullchain.pem; # 
    managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/website.com/privkey.pem; # 
    managed by Certbot


    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri $uri/ =404;
    }

推荐答案

在此线程中找到答案反应路由器和nginx

我要做的是将/etc/nginx/sites-available/default 中的 default 配置文件修改为:

What I had to do was modify default configuration file in /etc/nginx/sites-available/default to:

    location / {
            # First attempt to serve request as file, then
            # as directory, then fall back to displaying a 404.
            try_files $uri /index.html;
    }

这篇关于React Router路由在Nginx create-react-app上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆