Deploy Nuxt with Nginx: Configure Static Resources and Cache Strategies

Before deploying a Nuxt application, ensure that the Nginx server is correctly installed and configured. Typically, you need to install the official Nginx package and verify the configuration file syntax using nginx -t. Additionally, ensure that Nginx supports Vue static file processing, including the parsing of .vue files, which usually relies on plugins such as nginx-express or nginx-vue.

Static Resource Configuration

Nuxt application static resources (such as images, fonts, CSS, and JS files) must be correctly mapped via Nginx paths. Within the server block, configure handling rules for location / and location /assets:

location / {  
  root /path/to/nuxt/app;  
  index index.html;  
  try_files $uri $uri/ /index.html;  
}  
location /assets {  
  alias /path/to/nuxt/app/assets;  
  add_header Cache-Control "max-age=31536000, public";  
}  

The above configuration ensures that Nuxt dynamic routes (such as /blog/1) are correctly mapped to the /assets directory while setting a long-term caching strategy via the Cache-Control header.

Cache Strategy Configuration

To optimize performance, configure cache strategies in Nginx to avoid redundant rendering. For example:

  • Use the Cache-Control header to limit cache duration:
    add_header Cache-Control "max-age=31536000, immutable";  
    
  • Implement strong caching via ETag:
    add_header Etag $uri;  
    
  • Set a shorter cache time for dynamic content (such as API responses):
    location /api {  
      proxy_pass http://api-server;  
      proxy_cache_valid 200 302 1h;  
      proxy_cache_valid 503 10m;  
    }  
    

Additionally, ensure that Nuxt's ssr option (in nuxt.config.js) is enabled so that Nginx can correctly handle dynamically generated HTML files.

Other Considerations

  • File Type Handling: Set correct MIME types for files such as .vue, .js, and .css, for example:
    add_header Content-Type application/javascript;  
    
  • Path Mapping: Ensure that Nginx's root directive points to the correct directory of the Nuxt project to prevent resource loading failures.
  • Logging Configuration: Record exceptions during deployment via access_log and error_log to facilitate troubleshooting.

Summary

When deploying a Nuxt application, precise configuration of static resource paths and cache strategies via Nginx is required to ensure performance and user experience. Reasonably setting Cache-Control and ETag can reduce server load, while optimizing resource loading efficiency through location blocks. Finally, verify the configuration file syntax and test the deployment results to ensure the Nuxt application runs stably in the production environment.