Nginx: Issue serving static assets (js, css, etc.) with multi locations

Viewed 128

For demonstrating purposes, I have a very basic app setup. It consists of two projects, app01 and app02 Both folders are int the apps folder

apps
├── app01
│   ├── index.html
│   ├── style.css
│   └── subpage
│       └── index.html
└── app02
    ├── index.html
    └── style.css

The actual alias works. When I go to my-apps.local:3460 I see Welcome to App 01 and when I go to my-apps.local:3460/blog I see Welcome to App 02 (Blog) However the CSS (or any other static file) is not loaded in my /blog location.

In my Nginx conf file for this project I have also set up very basic:

listen      *:3460;
server_name example.com;

location ~* ^/blog2 {
  alias /Users/username/test/apps/app2/;
  try_files $uri index.html =404;
  index index.html;
}

location /blog1 {
  alias /Users/username/test/apps/app1/;
  try_files $uri index.html =404;
  index index.html;
}
1 Answers
location /blog1 {
  alias /example.com/apps/app01;
}  

location /blog2 {
  alias /example.com/apps/app02;
} 

apps/app01/index.html

Your HTML files must use relative links for all URIs. Absolute URIs will point to the root of your server, which would bypass the "/blog1" interception

https://example.com/blog1/

<link rel="stylesheet" href="style.css">

Welcome to 01

apps/app01/subpage/index.html

For subpages, maintain the use of relative links, but define the relative path root with the <base> tag.

https://example.com/blog1/subpage/

<base href="/blog1/"> 
<link rel="stylesheet" href="style.css">

Welcome to subpage 01

Alternatively, you could omit <base> and maintain parent ../ folder locations, which become cumbersome when files are moved.

<link rel="stylesheet" href="../style.css">
Related