How to Serve Angular App with Nginx: Simple Guide
To serve an Angular app with
nginx, build your Angular project using ng build --prod and configure nginx to serve the static files from the dist/ folder. Use a server block with root pointing to the Angular dist directory and add a fallback try_files $uri $uri/ /index.html; to support Angular routing.Syntax
This is the basic nginx server block syntax to serve an Angular app:
server { ... }: Defines the server configuration.listen 80;: Listens on port 80 for HTTP requests.server_name your_domain.com;: Your domain or IP address.root /path/to/angular/dist/;: Path to Angular's built files.index index.html;: Default file to serve.try_files $uri $uri/ /index.html;: Redirects all unmatched routes toindex.htmlfor Angular routing.
nginx
server {
listen 80;
server_name your_domain.com;
root /var/www/angular-app/dist/your-app-name/;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}Example
This example shows a complete nginx configuration to serve an Angular app built in /var/www/angular-app/dist/my-angular-app/. It listens on port 80 and supports Angular's client-side routing.
nginx
server {
listen 80;
server_name example.com;
root /var/www/angular-app/dist/my-angular-app/;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
error_page 404 /index.html;
}Common Pitfalls
Common mistakes when serving Angular apps with nginx include:
- Not using
try_files $uri $uri/ /index.html;which breaks Angular routing and causes 404 errors on page refresh. - Setting
rootto the wrong directory, so files are not found. - Forgetting to build the Angular app before serving, so
distfolder is missing. - Not setting correct permissions on the
distfolder, causing access errors.
Wrong example:
location / {
try_files $uri $uri/ =404;
}This returns 404 on Angular routes. The correct way is:
location / {
try_files $uri $uri/ /index.html;
}Quick Reference
Summary tips for serving Angular apps with nginx:
- Always build your Angular app with
ng build --prodbefore deploying. - Set
rootto the Angulardistfolder path. - Use
try_files $uri $uri/ /index.html;to enable Angular routing. - Check file permissions to allow
nginxaccess. - Reload
nginxafter config changes withsudo nginx -s reload.
Key Takeaways
Build your Angular app with production flag before serving with nginx.
Set nginx root to the Angular dist folder containing index.html.
Use try_files directive to serve index.html for client-side routing.
Check permissions and reload nginx after configuration changes.
Avoid 404 errors on refresh by properly configuring try_files.