nginx部署单页应用解决history路由访问404问题

1、关键点,重定向

location / {
  try_files $uri $uri/ /index.html;
}

2、部署在二级目录时,在地址栏直接回车会出错
注意,这段代码不能少

location / {
           root D:\projects\DataSourceUI\dist;
           try_files $uri $uri/ /index.html;
        }

最终配置如下:

server {
        listen       9000;
    #  listen       somename:8080;
        server_name  localhost;
        charset utf-8;

        location / {
           root D:\projects\DataSourceUI\dist;
           try_files $uri $uri/ /index.html;
        }
        location /dbconnection-ui {
           add_header 'Access-Control-Allow-Origin' '*';
           add_header 'Access-Control-Allow-Credentials' 'true';
           add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
           add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
           
           # 这里是alias而不是root
           alias D:\projects\DataSourceUI\dist; 
           index index.html index.htm;
           try_files $uri $uri/ /index.html;
        }
        location /data-source {
          if ($request_method = 'OPTIONS') {
              add_header 'Access-Control-Allow-Origin' '*';
              add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
              add_header 'Access-Control-Max-Age' 1728000;
              add_header 'Content-Type' 'text/plain charset=UTF-8';
              add_header 'Content-Length' 0;
              return 204;
          }
          if ($request_method = 'POST') {
              add_header 'Access-Control-Allow-Origin' *;
              add_header 'Access-Control-Allow-Credentials' 'true';
              add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
              add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
          }
          if ($request_method = 'GET') {
              add_header 'Access-Control-Allow-Origin' *;
              add_header 'Access-Control-Allow-Credentials' 'true';
              add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
              add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
          }
          # 匹配data-source之后的路径和参数
          rewrite  ^.+data-source/?(.*)$ /$1 break;
          include  uwsgi_params;
          # 实际调用的API
          proxy_pass http://xxx:8888;
        }
    }

你可能感兴趣的:(nginx部署单页应用解决history路由访问404问题)