nginx部署react应用,刷新路由报404

nginx部署react单页应用时,如果跳转到某一个路由,然后刷新当前路由,会报404.

个人认为:react为单页应用,加载页面靠路由,而路由不是真实的路径,要靠js找页面。而刷新路由后,按当前路径去nginx加载页面当然加载不到。如当前项目路径为https://www.xxx.com/xxx/,nginx上的配置为:

server {
listen 80;
server_name https://www.xxx.com;
location / {
    root xxx;
    index  index.html index.htm;
}
}
登录后复制

当请求https://www.xxx.com/xxx时,会到nginx下面找到该路径,然后加载index.html。现在切换到路由https://www.xxx.com/xxx/home,刷新页面后,实际请求的是xxx目录下home项目里的index.html。如此,就报404了。

正确配置如下,包括80和443的配置:

server {
listen 80;
server_name https://www.xxx.com;
location / {
    root xxx;
    index  index.html index.htm;
    rewrite ^/(.*)/(.*\.js$) /$1/$2 break;
        rewrite ^/(.*)/(.*\.map$) /$1/$2 break;
        rewrite ^/(.*)/(.*\.css$) /$1/$2 break;
        rewrite ^/(.*)/(.*\.(png|jpg|gif)$) /$1/$2 break;
    rewrite ^/(.*)/(.*\.(ttf|woff|woff2|svg|otf|eot)$) /$1/$2 break;
        rewrite ^/(.*)/ /$1/index.html break;
}
}
server {
    listen       443;
    server_name  54.222.208.17;
    ssl                  on;
 ssl_certificate      /etc/nginx/your.pem;
 ssl_certificate_key  /etc/nginx/your.key;
 ssl_session_timeout  5m;
    #charset koi8-r;
    #access_log  logs/host.access.log  main;
    location / {
        root xxx;
        index  index.html index.htm;
        rewrite ^/(.*)/(.*\.js$) /$1/$2 break;
        rewrite ^/(.*)/(.*\.map$) /$1/$2 break;
        rewrite ^/(.*)/(.*\.css$) /$1/$2 break;
        rewrite ^/(.*)/(.*\.(png|jpg|gif)$) /$1/$2 break;
 rewrite ^/(.*)/(.*\.(ttf|woff|woff2|svg|otf|eot)$) /$1/$2 break;
        rewrite ^/(.*)/ /$1/index.html break;
    }
}
登录后复制

以上就是nginx部署react刷新404如何解决的详细内容,更多请关注Work网其它相关文章!

09-06 19:51