React Router BrowserRouter leads to “404 Not Found - nginx ” error when going to subpage directly without through a home-page click

后端 未结 5 880
旧巷少年郎
旧巷少年郎 2020-12-05 00:10

I am using React Router for routing for a multi-page website. When trying to go to a sub page directly https://test0809.herokuapp.com/signin you\'d get a \"404 Not Found -ng

相关标签:
5条回答
  • 2020-12-05 00:49

    You can see my project: https://github.com/hongnguyenhuu96/honnh96 where you should put all codes in your create-react-app folder to react-ui folder and keep the others unchange. After that deloy to heroku, remember to config the deploy evironment to nodejs. It will works, good luck! It also deployed on heroku at: http://hongnh.herokuapp.com/

    0 讨论(0)
  • 2020-12-05 00:52

    two step solution (step 1 is mentioned in React-Router README https://github.com/mars/create-react-app-buildpack#routing-clean-urls):

    Step 1, add a static.json file to the root:

    {
     "root": "build/",
     "clean_urls": false,
     "routes": {
       "/**": "index.html"
     }
    }
    

    Step 2, add this Heroku buildpack: https://github.com/heroku/heroku-buildpack-static.git

    0 讨论(0)
  • 2020-12-05 00:58

    Just simply add try_files $uri $uri/ /index.html; to location / block in NGINX configuration file like this:

    server {
       listen       80;
       server_name  localhost;
    
       location / {
           root   /build;
           index  index.html;
           try_files $uri $uri/ /index.html;
       }
    }
    
    0 讨论(0)
  • 2020-12-05 01:01

    On location add this

    location / {
    try_files $uri /index.html;
    }
    
    0 讨论(0)
  • 2020-12-05 01:07

    The problem is that nginx doesn't know what to do with /signin. You need to change your nginx config (usually in /etc/nginx/conf.d/) to serve your index.html regardless of the route. Here is a sample nginx config that might help:

    server {
      listen 80 default_server;
      server_name /var/www/example.com;
    
      root /var/www/example.com;
      index index.html index.htm;      
    
      location ~* \.(?:manifest|appcache|html?|xml|json)$ {
        expires -1;
        # access_log logs/static.log; # I don't usually include a static log
      }
    
      location ~* \.(?:css|js)$ {
        try_files $uri =404;
        expires 1y;
        access_log off;
        add_header Cache-Control "public";
      }
    
      # Any route containing a file extension (e.g. /devicesfile.js)
      location ~ ^.+\..+$ {
        try_files $uri =404;
      }
    
      # Any route that doesn't have a file extension (e.g. /devices)
      location / {
        try_files $uri $uri/ /index.html;
      }
    }
    
    0 讨论(0)
提交回复
热议问题