How to deploy Vue with Nginx on sub-path

Pawat Siriwattanayotin
HLab
Published in
3 min readOct 11, 2020

It is useful to serve application on sub-path when you have multiple applications on the same domain. Alternatively, you can deploy each application on sub-domain. But what if you have to reserve sub-domain for another purpose like tenant name. Using sub-path is the way to go. In this post, I will walk you through step-by-step deploying App A on /app-a.

Prerequisite

  • Basic Vue
  • Basic Nginx
  • Basic Docker

Example code in this tutorial is available here.

Serve on sub-path locally

Locally running Vue on sub-path is straight forward with 2 points of configuration.

  • vue.config.js (If you don’t have one, create it at root of repo.)
  • .env

Now try run serve. You will get App A working on sub-path like this.

Before move on to next step, I would like you to check on all requests to make a Vue page on Network tab of developer tools.

Notice that all Vue bundle files also serve on sub-path. Look at “Request URL”.

On production mode, the bundle files look similar to local mode.

Understanding Nginx

We will start with example nginx.conf from deployment guide here.

The highlight of this code is at location block. We will investigate how Nginx works on 2 cases.

a. Request to http://domain.com/

  1. [location /]: It matches location / block
  2. [root /app]: Change directory to /app
  3. [try_files $uri]: Try looking for / file in /app. Aww it is not file.
  4. [try_files $uri $uri/]: Try looking for / directory in /app. Aww nothing match.
  5. [try_files $uri $uri/ index.html]: Finally looking for /index.html in /app. Ah Ha there it is.

b. Request to http://doamin.com/js/about.xx.js

  1. [location /]: It matches location / block
  2. [root /app]: Change directory to /app
  3. [try_files $uri]: Try looking for /js/about.xx.js in /app. Ah Ha there it is.

If we use the same nginx config for sub-path, Nginx will show nothing when requesting to http://domain.com/app-a.

Let fix nginx.conf on location block with this snippet.

This time Nginx can find both asset files and index.html on sub-path.

Time to Deploy

Combining all pieces together.

  • .env.production (environment variables for production mode)
  • nginx.conf
  • Dockerfile
  • Build & Run

Reference

  1. Dockerize Vue App: https://cli.vuejs.org/guide/deployment.html#docker-nginx
  2. Nginx try_files Definition: http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files

This is my first blog. All feedbacks are welcome.

--

--

Pawat Siriwattanayotin
HLab
Editor for

Full stack developer, DevOps, CTO, Learner, Football Lover