Angular部署后assets图片无法访问的路径配置问题
Hey there, I’ve dealt with this exact problem when deploying Angular apps to subdirectories on a server—let’s get your images showing up correctly!
The Root Cause
When you build with ng build --prod without adjusting the base href, Angular defaults to using the server root (/) as the base for all resource paths. That’s why your server was looking for images at abc.host.com/~user1/assets/... instead of including the myapp subdirectory.
Step-by-Step Solution
Update the base href in
index.html:
Replace your existing<base href>tag with:<base href="./">Using
./tells Angular to resolve all paths relative to the current directory (where yourindex.htmlis hosted—abc.host.com/~user1/myapp/in your case), instead of the server’s root.Use the correct image source path:
For your image tags, use this relative path (no leading slash or../):<img src="assets/img/img1.jpg" alt="My Image">Since we set the base href to the app’s directory, Angular will now resolve this path to
abc.host.com/~user1/myapp/assets/img/img1.jpg—exactly the location of your images.
This setup keeps everything using relative paths, so your app will work both locally (on localhost:4200) and when deployed to the subdirectory.
内容的提问来源于stack exchange,提问作者Gero

