dockernginxnginx-confignginx-location

How to make multiple locations open the same index.html file in nginx?


I am developing a website (html/css/js, no php involved). Due to requirements, I use a docker container with an nginx image inside.

I have two HTML files that are the same. One should open as root (e.g. www.example.com) and the other one should open when the subdir subdirectory is hit (e.g. www.example.com/subdir).

I do not want to have the same file copied multiple times due to obvious reasons.

In nginx, how can I make the www.example.com automatically redirect to www.example.com/subdir or vice versa (the www.example.com/subdir redirect to www.example.com)?

I tried various things but I keep receiving 403 forbidden.


Solution

  • Okay, so the following solution should work for you:

    location = / {     # Serving that index.html file when requesting / (root)
      index /subdir/index.html;
    }
    
    location /subdir {    # Serve that subdirectory how you want, e.g. like that
      root /var/www/html;
      index index.html;
    }