vue-router 设置 history 模式
vue 项目往往会搭配 vue-router 官方路由管理器,它和 vue.js 的核心深度集成,让构建单页面应用变得易如反掌。vue-router 默认为 hash 模式,使用 URL 的 hash 来模拟一个完整的 URL,所以当 URL 改变时,页面不会重新加载,只是根据 hash 来更换显示对应的组件,这就是所谓的单页面应用。

但是使用默认的 hash 模式时,浏览器 URL 地址中会有一个 # ,这跟以往的网站地址不太一样,可能也会让大部分人不习惯,甚至觉得它很丑。

想要去掉地址中的 # 也不难,只要更换 vue-router 的另一个模式 history 模式即可做到。

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes:[...]
})
当你使用 history 模式时,URL 就变回正常又好看的地址了,和大部分网站地址一样,例如:http://2177.com.cn/name/id

不过,这种模式有个坑,不仅需要前端开发人员将模式改为 history 模式,还需要后端进行相应的配置。如果后端没有正确的配置好,当你访问你的项目地址时,就会出现 404 ,这样可就更不好看了。

官方给出了几种常用的后端配置例子:

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>



nginx


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



原生 Node.js


const http = require('http')
const fs = require('fs')
const httpPort = 80

http.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)
})


Internet Information Services (IIS)
<?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>
				</rule>
			</rules>
		</rewrite>
	</system.webServer>
</configuration>