Angular开发服务器部署生产构建文件后路由访问404问题求助
Hey there, I totally get this frustration—SPA routing can be tricky when moving between servers! The issue here is that Angular is a single-page application (SPA), meaning all your routes are handled client-side by Angular's router, not by Apache. When you directly visit pages.100pins.com/client/lrr/login, Apache tries to look for a physical file or directory at that path, which doesn't exist (since your build only has index.html and static assets). The production server already has the right configuration to handle this, but your dev server is missing it.
Here's how to fix it step by step:
First, enable Apache's Rewrite Module
This module lets us redirect requests toindex.htmlwhen no physical file exists. Run these commands (adjust based on your OS):# For Ubuntu/Debian sudo a2enmod rewrite sudo systemctl restart apache2 # For CentOS/RHEL sudo systemctl enable httpd sudo systemctl restart httpdCreate a
.htaccessfile in your project's root directory
This file will tell Apache how to handle SPA routes. Add these lines:RewriteEngine On # Don't rewrite actual files or directories RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Redirect all other requests to index.html RewriteRule ^(.*)$ /index.html [L]This rule checks if the requested path points to a real file or folder—if not, it sends the request to
index.html, where Angular's router can take over and load the correct component.Update your Apache Virtual Host configuration
Make sure your virtual host allows.htaccessoverrides. Find your site's config file (usually in/etc/apache2/sites-available/or/etc/httpd/conf.d/) and add this inside the<Directory>block pointing to your project's files:<Directory /path/to/your/angular/build/files> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory>Save the file and restart Apache again to apply the changes.
Once you've done these steps, direct access to any Angular route should work just like it does on the production server!
内容的提问来源于stack exchange,提问作者yash

