Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add context path for an app on nginx

Nginx servers all the static content from the root directory to the root URL. For example if the root content location is configured as /usr/share/nginx/html which contains a file /usr/share/nginx/html/foo.html, then the url http://localhost/foo.html will serve that html file. I want to prefix a context path in the URL such that http://localhost/myapp/foo.html should serve /usr/share/nginx/html/foo.html file.

I tried changing the location and adding an alias but that gives a 404.

  location / {
    root   /usr/share/nginx/html;
    index  index.html index.htm;
  }

  location /myapp/ {
    alias   /usr/share/nginx/html/;
  }

I also want that http://localhost/myapp should serve /usr/share/nginx/html/index.html

I'm using nginx's 1.12.1-alpine docker image

like image 416
ares Avatar asked Sep 20 '25 10:09

ares


1 Answers

Try this

  index  index.html index.htm;
  location / {
    root   /usr/share/nginx/html;
  }

  location /myapp/ {
    alias   /usr/share/nginx/html/;
  }

If that doesn't work then try below

  index  index.html index.htm;
  location / {
    root   /usr/share/nginx/html;
  }

  location /myapp/ {
    alias   /usr/share/nginx/html/;
    try_files $uri $uri/ =404;
  }

Edit-1

If you want it to work without trailing / then you should use below

location ~ /app(/.*)?$ {
   alias   /usr/share/nginx/html/;
   try_files $uri $uri/ =404;
}
like image 150
Tarun Lalwani Avatar answered Sep 23 '25 11:09

Tarun Lalwani