Add context path for an app on nginx

12,189

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;
}
Share:
12,189
ares
Author by

ares

Updated on June 04, 2022

Comments

  • ares
    ares almost 2 years

    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

  • ares
    ares over 6 years
    Thanks for your response - I'm trying with a trailing slash as I've written it in the question as well.
  • Tarun Lalwani
    Tarun Lalwani over 6 years
    The config is 100% correct. I have tested it locally. I guess you have some other default config also lying around in your nginx config which may be the issue. Add the output of find . -name "*.conf" in the folder where your nginx.conf folder is present
  • ares
    ares over 6 years
    That worked after some trying. The only thing that root url without a trailing slash (http://localhost/myapp) returns 404 where http://localhost/myapp/ returns index.html
  • Elouan Keryell-Even
    Elouan Keryell-Even over 4 years
    Would you mind explaining why the OP's conf was returning 404? I fail to understand what the problem was
  • Tarun Lalwani
    Tarun Lalwani over 4 years
    I think index index.html was not outside that is why.