Vuejs+Webpack部署

本文介绍如何解决Vue.js结合Webpack项目中子页面URL刷新后出现404的问题。详细介绍了从hash模式切换至history模式的过程,并针对Apache、nginx、Node.js等不同服务器环境提供了具体的配置方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vuejs+webpack部署子页面刷新404问题

使用vuejs+webpack在本地开发的时候很顺利,但在打包部署后子页面不能通过url地址直接访问到,只能通过主页点击前往各子页面。

router

vuejs的router默认使用的是hash,但是这种模式下的url看上去的体验很不好。因此改用history模式,在这种模式下的url看起来就会好很多,也符合平时的使用习惯。

在本地开发阶段并未发现问题,但在使用webpack打包部署后,出现了子页面不能直接通过url地址访问到的问题(也就是子页面刷新后会出现404)。

在查看官方文档后发现,虽然是一个单页面应用,但是需要对服务器进行适当的配置才可以。

解决办法

这个解决办法是来自vuejs的官方文档,经测试可以解决这个问题,所以当了一次搬运工,希望对大家有帮助。

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

Native Node.js

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

http.createServer((req, res) => {
  fs.readFile('index.htm', 'utf-8', (err, content) => {
    if (err) {
      console.log('We cannot open "index.htm" 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)

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 hosting

{
  "hosting": {
    "public": "dist",
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

Caveat

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '*', component: NotFoundComponent }
  ]
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值