zoukankan      html  css  js  c++  java
  • 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;
    }

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

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

     







  • 相关阅读:
    OpenStack 中的neutron-server启动过程
    NYOJ 284 坦克大战 【BFS】+【优先队列】
    HDSF主要节点解说(二)工作原理
    SQL SERVER中的流程控制语句
    Android 自己定义View (二) 进阶
    JNI学习积累之一 ---- 常用函数大全
    Android NDK开发之Jni的数据类型
    CMakeListx.txt 编辑语法学习
    用CMake代替makefile进行跨平台交叉编译
    Android 开发--CMakeList调用本地so文件
  • 原文地址:https://www.cnblogs.com/createGod/p/7259958.html
Copyright © 2011-2022 走看看