react,vue等部署单页面项目时,访问刷新出现404问题

1. 问题描述:

上个礼拜开发了个简单的单页面移动端页面,地址,然后进入到文章详情,刷新浏览器,发现浏览器出现404了,what happen? 如下图:

image.png

2. 问题原因:

刷新页面时访问的资源在服务端找不到,因为react-router设置的路径不是真实存在的路径。
如上的404现象,是因为在nginx配置的根目录/alidata/www/mgeekjc下面压根没有article这个真实资源存在,这些访问资源都是在js里渲染的。

服务端nginx的一开始配置如下(假设域名为:m.geekjc.com):

server {
    listen      80;
    server_name m.geekjc.com;
    
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    #gzip_http_version 1.0;
    gzip_comp_level 2;
    gzip_types text/plain application/javascript application/x-javascript text/javascript application/json text/css application/xml application/x-httpd-php image/jpeg image/gif image/png;
    gzip_vary off;
    gzip_disable "MSIE [1-6]\."; 

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;
    
    location / {
        root /alidata/www/mgeekjc;
        index index.html;
}

如上出现404的原因是由于在这个域名根目录/Data/app/xqsj_wx/dist下面压根就没有article这个真实目录存在。

3. 问题解决:

在nginx配置里添加react-route的跳转设置(这里首页是index.html,如果是index.php就在下面对应位置替换),正确配置如下:

server {
    listen      80;
    server_name m.geekjc.com;
    
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    #gzip_http_version 1.0;
    gzip_comp_level 2;
    gzip_types text/plain application/javascript application/x-javascript text/javascript application/json text/css application/xml application/x-httpd-php image/jpeg image/gif image/png;
    gzip_vary off;
    gzip_disable "MSIE [1-6]\."; 

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;
    
    location / {
        root /alidata/www/mgeekjc;
        try_files $uri $uri/ @router;
        index index.html;
    }    
    
    location @router{
        rewrite ^.*$ /index.html last;
    }

    #error_page  404              /404.html;

    # redirect server error pages to the static page /50x.html
    #
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

}

重启nginx后,问题就迎刃而解了。
如图:


image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,742评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,224评论 19 139
  • 配置运行Nginx服务器用户(组) 用于配置运行Nginx服务器用户(组)的指令是user,其语法格式为: use...
    吃瓜的东阅读 10,035评论 0 41
  • 我曾说过,我常常有,想拔除美女同事嘴里,两颗虎牙的冲动。当她知道我的冲动后,非但没有讨厌我,反倒对我喜欢的不得了。...
    一老碗面阅读 1,675评论 0 3
  • 很多年前,我也刚入职场,同事迟到总是让我给她签到,次数多了难免被人发现,于是我与她一起签了警告通知书,扣工资是小...
    酷雪冰凌阅读 4,093评论 8 5

友情链接更多精彩内容