How to solve nginx deployment react refresh 404

WBOY
Release: 2023-05-15 18:01:19
forward
3441 people have browsed it

nginx部署react刷新404的解决办法:1、修改Nginx配置为“server {listen 80;server_name https://www.xxx.com;location / {root xxx;index  index.html index.htm;...}”;2、刷新路由,按当前路径去nginx加载页面即可。

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;
}
}
Copy after login

当请求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;
    }
}
Copy after login

The above is the detailed content of How to solve nginx deployment react refresh 404. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template