How to Serve Vue App with Nginx: Simple Guide
To serve a Vue app with
nginx, build your Vue app using npm run build to generate static files, then configure nginx to serve the dist folder as a static site. Use a server block pointing to the build directory and enable fallback to index.html for SPA routing.Syntax
The basic nginx configuration to serve a Vue app includes setting the root to the Vue build directory, defining the index file, and configuring try_files to handle SPA routing by redirecting all requests to index.html.
Key parts:
root: Path to the Vue app'sdistfolder.index: The main HTML file, usuallyindex.html.try_files: Tries to serve requested files, falls back toindex.htmlfor client-side routing.
nginx
server {
listen 80;
server_name your-domain.com;
root /path/to/vue-app/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}Example
This example shows a complete nginx server block to serve a Vue app built into the dist folder. It listens on port 80 and serves static files. The try_files directive ensures Vue's client-side routing works by redirecting unknown paths to index.html.
nginx
server {
listen 80;
server_name example.com;
root /var/www/vue-app/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico|woff|woff2|ttf|eot)$ {
expires 1y;
access_log off;
}
}Output
Nginx starts and serves the Vue app at http://example.com with static assets cached for 1 year.
Common Pitfalls
Common mistakes when serving Vue apps with nginx include:
- Not using
try_files $uri $uri/ /index.html;which breaks client-side routing. - Setting the wrong
rootpath, causing 404 errors. - Forgetting to build the Vue app before serving, so the
distfolder is missing. - Not configuring caching headers for static assets, leading to slow load times.
nginx
server {
listen 80;
server_name example.com;
root /var/www/vue-app/dist;
index index.html;
location / {
# Wrong: missing try_files causes routing issues
# try_files $uri $uri/ /index.html;
}
}Quick Reference
Tips for serving Vue apps with nginx:
- Always run
npm run buildto create thedistfolder before deploying. - Use
try_files $uri $uri/ /index.html;to support Vue Router in history mode. - Set caching headers for static files to improve performance.
- Check file permissions so
nginxcan read the files.
Key Takeaways
Build your Vue app with npm to generate static files before serving with nginx.
Configure nginx root to point to the Vue app's dist folder.
Use try_files directive to enable client-side routing support.
Set caching headers for static assets to improve load speed.
Verify nginx has permission to access the Vue app files.