nginx配置访问白屏问题

352 阅读1分钟

问题复显

当跳转 http://xxxxx/your/path 时 显示白屏

但正常访问http://xxxxx 路径显示正常

由于vue开发的为spa应用。打包后一个dist文件

  • dist
    • css文件
    • html文件
    • static文件夹

后在nginx会进行一次配置

server {
    	listen 80;

    	location /apiset/ { //接口请求
            proxy_pass http://x x x x:3000/apiset/;
            proxy_set_header Host $host:$server_port;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
       
    	location / {
      	    root /your/html/path;
            try_files $uri $uri/ /index.html;
            add_header Cache-Control "no-cache, no-store, must-revalidate";
        	add_header Pragma "no-cache";
        	add_header Expires 0;
            ;
        }
        
    }

问题原因

当访问http://xxxxx/your/path 时返回一个html文件,在根据内部的link,script标签进行对css js的访问,问题出在这块

<!doctype html>
<html lang="en">
  <head>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" href="./static/favicon.ico" />
    <link rel="stylesheet" href="./static/app-loading.css" />
    <title>xxxx</title>
 
    
  </head>
  <body>
    <div id="app">
      <div id="app-loading"></div>
    </div>
    
    
  </body>
</html>

此时html上面访问的css路径为相对路径,在vite配置内部是base属性,base属性为‘’

当访问的路径为 http://xxxxx/your/path
<link rel="icon" href="./static/favicon.ico" />解读为
<link rel="icon" href="http://xxxxx/your/static/favicon.ico" /> 

因为打包结构不存在‘your’这个文件夹导致找不到文件触发 try_files uriuri uri/ /index.html 规则把应该获取css/js文件变为返回html文件导致白屏问题。

解决

将内部相对路径修改为绝对路径,或者nginx配置重写

vite
export default (_configEnv: ConfigEnv): UserConfigExport => {
 

  return {
    base: "/",
    。。。
 
  }
}
或
nginx
server {
    	listen 80;

    	location /apiset/ { //接口请求
            proxy_pass http://x x x x:3000/apiset/;
            proxy_set_header Host $host:$server_port;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        }
       
    	location / {
      	    root /your/html/path;
            try_files $uri $uri/ /index.html;
            add_header Cache-Control "no-cache, no-store, must-revalidate";
            add_header Pragma "no-cache";
            add_header Expires 0;
            rewrite ^/your/(.*)$ /$1 break; //重写your路径
        }
        
    }