React Router路由无法在nginx create-react-app上运行

时间:2018-03-13 08:11:25

标签: reactjs nginx react-router create-react-app

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

如果我在localhost:3000/second上进行测试,那就完美了。

当我使用nginx在ubuntu服务器上上传时,我尝试www.website.com,它可以正常工作。当我尝试使用www.website.com/second时,它会给我404 not found。我正在使用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的/位点可用/默认 这是来自服务器的配置文件

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;
    }

4 个答案:

答案 0 :(得分:7)

答案可以在这个帖子中找到 React-router and nginx

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

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

答案 1 :(得分:1)

如果您希望在Dockerfile中执行此操作并使用React运行nginx应用,请参见以下答案。

https://stackoverflow.com/a/61753597/4388776

这解决了React Router问题,您允许nginx将来自不同端点的流量直接路由到您的React Application。

答案 2 :(得分:0)

在实时服务器上对我有效的解决方案:

server {
        listen 80;
        listen [::]:80;

        root /var/www/example.com;
        index index.html index.htm index.nginx-debian.html;

        server_name example.com www.example.com;

        location / {
                try_files $uri $uri/ /index.html;
        }
}

答案 3 :(得分:-2)

您需要通过/ etc / nginx / sites-available /.

配置nginx

将有一个模板默认文件,因此如果您想保留它,请复制它。执行此操作后,使用任何文本编辑器并将/ etc / nginx / sites-available / default更改为以下内容:

server {
   listen 80 default_server;
   root /var/www/[Your repo name]/build;
   server_name [your.domain.com] [your other domain if you want to];
   index index.html index.html;
   location / {
   }
}
相关问题