vue,react,angular本地配置nginx 环境单页面应用

一、起因:项目使用VUE,和react。构建单页面应用。在nginx的环境下只有一个index.html入口。这时候默认能够访问到vue,和react 路由

配置中的首页。内部连接也能够跳转但是不能给刷新也面。刷新页面后就为变为404页面。

二、原因:nginx 在解析路径的时候:比如: localhost/a 这个路由。其实nginx 在解析路径 时候。为去root根路径下去找a文件。但是找不到。所有就会报错。

但是在单页面应用中localhost/a 其实是 VUE, 和react 内部制定的路由规则。这时候。就出现问题了。该如何配置呢?

三、配置文件。

 server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        location /home {
            rewrite .* /index.html break;
            root   html;
        }
        location /strategy {
            rewrite .* /index.html break;
            root   html;
        }
        location /wealthMange {
            rewrite .* /index.html break;
            root   html;
        }
        location /aboutUs {
            rewrite .* /index.html break;
            root   html;
        }
        location /contacts {
             rewrite .* /index.html break;
             root   html;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }    
    }

通过rewrite .* /index.html break;把一切path重写为/index.html,break很重要,它使得url的匹配结束,最终服务返回的文档其实是/htm/index.html

那个break决定了浏览器里的url是不变的,而http响应的文档其实就是index.html,而浏览器上的path,会自动的被vue-router处理,进行无刷新的跳转,我们看到的结果就是path对应了那个页面!

location /home {
            rewrite .* /index.html break;
            root   html;
}
当我们浏览器输入这样 localhost/home 是 重定向为 rewrite .*/index.html break; root html; 相当于我们home 页面。就样就OK 啦。
四、Apache 下的单页面应用配置
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

.htaccess 把 这个文件的内容改为上面的代码就可以了。

五、nginx的简单配置方法

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

一行代码就可以搞定。不用写那么多路由规则啦。

哈哈是不是很爽啊。???