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;
}

一行代碼就可以搞定。不用寫那么多路由規則啦。

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

 







 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM