nginxnginx-reverse-proxynginx-location

Nginx catch-all routes, except root route


So, I have a URL Shortener website, and I want ONLY the root path to be served via static files and other routes to be redirected to their destination via API.

I found the solution with location = /, but it didn't help much.

server {
    listen 443 ssl;
    server_name domain.com;

    ...

    # Home page
    location = / {
        root /usr/share/nginx/html;
        index  index.html;
    }

    # Redirects
    location / {
        proxy_pass http://api:3000/v1/urls/redirect$uri;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Solution

  • Directive index would causes an internal redirect, and the request can be processed in a different location, a / request will actually be processed in the second location as /index.html.
    You can config as:

    server {
        
      ...
      
      location = / {
        index /c0g2af/index.html;
      }
    
      location / {
            proxy_pass   http://api:3000/v1/urls/redirect$uri;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    
        location /c0g2af/ {
            root /usr/share/nginx/html;
        }
        
    }
    

    Create a directory in /usr/share/nginx/html and name it as random code, for example c0g2af.