Reputation: 43
So i have 3 different angular projects, pj1, pj2 and pj3 which i'm trying to deploy using nginx. The aim is to have the routes as follows:
www.mysite.com/ ---> loads the pj1
www.mysite.com/pj2 ---> loads the pj2
www.mysite.com/pj3 ---> loads the pj3
The folder structure looks like this:
My nginx configuration file looks like this:
server {
root /usr/share/nginx/my-projects;
location /pj1/ {
autoindex on;
try_files $uri$args $uri$args/ /pj1/index.html;
}
location /pj2/ {
autoindex on;
try_files $uri$args $uri$args/ /pj2/index.html;
}
location /pj3/ {
autoindex on;
try_files $uri$args $uri$args/ /pj3/index.html;
}
location / {
try_files $uri$args /pj1/index.html;
}
}
I am building each project with the following command:
ng build --prod --aot=true --buildOptimizer=true --base-href /pj1/ --deploy-url /pj1/
This is for building the pj1 project as an example, the other ones follow the same pattern.
The images which are in the html are like this, for example:
<img src="assets/img1.jpg" />
It loads correctly, both on server and locally. However, the images which are referenced in the scss files only load whether on server or locally, depending on how i define their paths. This path, for example, works perfectly on my local machine, but does not work on the server:
background-image: url(/assets/img1.svg);
And when i change to the following path, i get an error on the cli saying that it could not load the resource:
background-image: url(assets/img1.svg);
Though it works if i put it manually with the inspector of the broswer when running on the server. So it works on the server, but not locally.
I don't know exactly what is causing this problem, perhaps angular is not referencing the correct root since it only goes wrong when i put the "/" at the beginning of the path, however if i don't put this there then it does not work on my local machine. Is there any solution to this? Something that functions both on local machine and server?
Upvotes: 0
Views: 1784
Reputation: 43
I found the solution! The problem happens due to a weird way that angular handles the paths to images in the css files, as mentioned in this answer here
So what worked for me was to let the paths as absolutes, like the following example:
background-image: url(/assets/img1.svg);
And add the following code to my angular.json file:
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
...
"rebaseRootRelativeCssUrls": true
This makes angular change the root of where the folder assets is going to be searched, so instead of searching for the images of my project one on www.mysite.com/assets/, for example, it will instead search on www.mysite.com/pj1/assets/ which is in fact just what i needed.
Upvotes: 1