2019独角兽企业重金招聘Python工程师标准>>>
1. 问题描述:
上个礼拜开发了个简单的单页面移动端页面,地址,然后进入到文章详情,刷新浏览器,发现浏览器出现404了,what happen? 如下图:
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后,问题就迎刃而解了。
如图: