前言
用過VueRouter
路由組件的應該都知道,VueRouter
有hash
和history
兩種模式。hash
模式會在url
中插入#
,history
模式下url
則看上去更加簡潔美觀。如果想要支持history
模式則必須要后端服務進行配合。
常用后端服務器配置方式請參考 后端配置例子
后端配置例子
注意:下列示例假設你在根目錄服務這個應用。如果想部署到一個子目錄,你需要使用 Vue CLI 的 publicPath 選項 (opens new window)和相關的 router base property (opens new window)。你還需要把下列示例中的根目錄調整成為子目錄 (例如用 RewriteBase /name-of-your-subfolder/ 替換掉 RewriteBase /)。
Apache
<IfModule?mod_rewrite.c>RewriteEngine?OnRewriteBase?/RewriteRule?^index\.html$?-?[L]RewriteCond?%{REQUEST_FILENAME}?!-fRewriteCond?%{REQUEST_FILENAME}?!-dRewriteRule?.?/index.html?[L]
</IfModule>
除了 mod_rewrite,你也可以使用 FallbackResource。
nginx
location?/?{try_files?$uri?$uri/?/index.html;
}
原生 Node.js
const?http?=?require('http')
const?fs?=?require('fs')
const?httpPort?=?80http.createServer((req,?res)?=>?{fs.readFile('index.html',?'utf-8',?(err,?content)?=>?{if?(err)?{console.log('We?cannot?open?"index.html"?file.')}res.writeHead(200,?{'Content-Type':?'text/html;?charset=utf-8'})res.end(content)})
}).listen(httpPort,?()?=>?{console.log('Server?listening?on:?http://localhost:%s',?httpPort)
})
基于 Node.js 的 Express
對于 Node.js/Express
,請考慮使用 connect-history-api-fallback
中間件 。
IIS
安裝 IIS UrlRewrite
在你的網站根目錄中創建一個 web.config 文件,內容如下:
<?xml?version="1.0"?encoding="UTF-8"?>
<configuration><system.webServer><rewrite><rules><rule?name="Handle?History?Mode?and?custom?404/500"?stopProcessing="true"><match?url="(.*)"?/><conditions?logicalGrouping="MatchAll"><add?input="{REQUEST_FILENAME}"?matchType="IsFile"?negate="true"?/><add?input="{REQUEST_FILENAME}"?matchType="IsDirectory"?negate="true"?/></conditions><action?type="Rewrite"?url="/"?/></rule></rules></rewrite></system.webServer>
</configuration>
Caddy
rewrite?{regexp?.*to?{path}?/
}
Firebase 主機
在你的 firebase.json 中加入:
{"hosting":?{"public":?"dist","rewrites":?[{"source":?"**","destination":?"/index.html"}]}
}
警告
給個警告,因為這么做以后,你的服務器就不再返回 404 錯誤頁面,因為對于所有路徑都會返回 index.html 文件。為了避免這種情況,你應該在 Vue 應用里面覆蓋所有的路由情況,然后再給出一個 404 頁面。
const?router?=?new?VueRouter({mode:?'history',routes:?[{?path:?'*',?component:?NotFoundComponent?}]
})
或者,如果你使用 Node.js 服務器,你可以用服務端路由匹配到來的 URL,并在沒有匹配到路由的時候返回 404,以實現回退。更多詳情請查閱 Vue 服務端渲染文檔 (opens new window)。
原生AspNetCore實現
現如今AspNetCore
完全不需要依賴IIS
即可進行部署,如何在AspNetCore
原生應用中進行支持VueRouter
的history
想必是很多人遇到到的問題之一,也許大部分人選擇使用hash
模式,因為它雖然丑點,但是不需要任何配置即可使用。為了帶給像我一樣強烈需要history
模式的用戶,索性寫了個中間件,經過測試,能夠完美支持VueRouter
組件history
模式的部署。
VueRouterHistory
VueRouterHistory
是實現原生AspNetCore
下支持VueRouter
的history
模式的中間件。
源碼已開源在Github: https://github.com/SpringHgui/VueRouterHistory
使用方法
通過
nuget
安裝VueRouterHistory
Install-Package?VueRouterHistory?-Version?1.0.2
注冊中間件
app.UseVueRouterHistory()
在app.UseRouting()
或app.MapControllers()
之后添加app.UseVueRouterHistory()
;
//?This?method?gets?called?by?the?runtime.?Use?this?method?to?configure?the?HTTP?request?pipeline.
public?void?Configure(IApplicationBuilder?app,?IWebHostEnvironment?env)
{if?(env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseExceptionHandler("/Home/Error");//?The?default?HSTS?value?is?30?days.?You?may?want?to?change?this?for?production?scenarios,?see?https://aka.ms/aspnetcore-hsts.app.UseHsts();}app.UseHttpsRedirection();app.UseStaticFiles();app.UseRouting();//?==============添加這一行即可================app.UseVueRouterHistory();app.UseAuthorization();app.UseEndpoints(endpoints?=>{endpoints.MapControllerRoute(name:?"default",pattern:?"{controller=Home}/{action=Index}/{id?}");});
}
將Vue編譯后的產物全部放置到
wwwroot
文件夾下開始體驗你的應用吧~
結語
VueRouterHistory
中間件的使用,讓我們免于對iis進行配置以實現history
模式部署,使項目不管是托管在IIS還是直接自托管模式,都不需要進行額外的配置。歡迎有需要的朋友通過VueRouterHistory
包進行支持history
模式,如遇到問題,請提交ISSU。