Search code examples
nginxnginx-config

NGINX locations matched not rules


at the moment i have an issue with NGINX. I like to serve a static HUGO generated html website. This website is is multi language (en, de) and stored in different folders.

└─ /usr/share/nginx/html/my-app/
   ├─ en/
   └─ fr/

So i have setup a NGINX configuration to handle en and de content requests in different locations.

http {
  ...
  server {
      listen                8080;
      server_name           localhost;
      index                 index.html;
      root                  /usr/share/nginx/html;

        location / {
            root           /usr/share/nginx/html/my-app/en
            index          index.html;
            try_files      $uri $uri/index.html =404;
        }

        location /de/ {
            root           /usr/share/nginx/html/my-app/de
            index          index.html;
            try_files      $uri $uri/index.html =404;
        }

        location /en-us/ {
            root           /usr/share/nginx/html/my-app/en
            index          index.html;
            try_files      $uri $uri/index.html =404;
        }
        ...
 }

At this point only http://localhost:8080 is served by NGINX. So the EN content is served.

But if i request http://localhost:8080/de or http://localhost:8080/de/ there is always an 404 error. I dont understand why the DE content is not found. There is a 1:1 location - folder matching?!

Also the virtuel path http://localhost:8080/any-lang or http://localhost:8080/any-lang/ is not working. My idea was if the path any-lang is requested, NGINX will use the en folder to serve content.

I would be happy about every suggestion or ideas!


Solution

  • Let me start with an example

    server {
    
        location /images/ {
            root /data;
        }
    }
    

    When you send a request to the /images/ address, then nginx looks for files in this path to serve it.

    /data/images/
    

    You have 2 choices

    1. The solution given by Richard in the comments (But keep in mind that the folder name must be the same as the address -> /en-us folder must be /usr/share/nginx/html/my-app/en-us

    2. Use alias instead of root

        location / {
            root           /usr/share/nginx/html/my-app/en;
            index          index.html;
            try_files      $uri $uri/index.html =404;
        }
    
        location /de {
            alias           /usr/share/nginx/html/my-app/de;
            index          index.html;
            try_files      $uri $uri/index.html =404;
        }
    
        location /en-us {
            alias           /usr/share/nginx/html/my-app/en;
            index          index.html;
            try_files      $uri $uri/index.html =404;
        }