background

For a production deployment project, the access paths of the Intranet and extranet are different. The Intranet is accessed based on the root directory of the domain name, while the extranet points to a subdirectory.

Eg. :

Vue – the router: the history mode network environment: 192.168.1.1:8080 / index. HTML web environment: domain.com/ttsd/index.html

Since the developed project is to be deployed on the client side, and the client does not want a separate domain name (or subdomain) for deployment, the packaged application needs to make some configuration changes.

Modifying a Configuration File

1. Change the packaged resource reference to a relative path and find assetsPublicPath under the build property in config/index.js

build: {
    ...
    assetsPublicPath: '/'// The configuration before modification is'/',}Copy the code

build/utils.js
publicPath
'.. /.. / '

if (options.extract) {
  return ExtractTextPlugin.extract({
    use: loaders,
    fallback: 'vue-style-loader',
    publicPath: '.. /.. / '// Modify path})}else {
  return ['vue-style-loader'].concat(loaders)
}
Copy the code

Modify the routing

In the route history mode, all routes are based on the root path, such as/XXXX. Since the deployment directory is unknown, we can obtain the currently accessed file path according to location.pathname to modify the route.

Vue-router provides a base attribute

Base type: string Default value: “/” Base path of the application. For example, if the entire single-page application service is under /app/, then base should be set to “/app/”.

Modifying routing codes

function getAbsolutePath () {
  let path = location.pathname
  return path.substring(0, path.lastIndexOf('/') + 1)}const routers = new Router({
  mode: 'history'.base: getAbsolutePath(),
  ...
})
Copy the code

At this point, the changes related to the packaging configuration are complete and the project is accessible. However, there is still a problem. If you jump to a route and refresh the page, the page will be blank and you need to modify the configuration of nginx.

Modify nginx configuration

The official nginx configuration is in the root directory, which is router.vuejs.org/zh-cn/essen…

location / {
  try_files $uri $uri/ /index.html; // Change it to try_files$uri $uri/ /dist/index.html;
}
Copy the code

Note: /dist can be modified according to the actual deployed website directory. Personal feelings can also be accessed dynamically through nginx built-in commands, which is not clear below.

After the

Reference article: Vue + Webpack + Nginx deployed in server not root to access 404 problems

Vue-cli Webpack template project construction and solution to the path problems when packaging