Pratik Vanjare
Pratik Vanjare

Reputation: 11

Nginx Alias route not working after adding location block

I have configured nginx alias, the expected behaviour is whenever there is https://demo-frontend.in/dl/uurl/orr, the request it should get served from /var/www/frontend_react/build/ directory. But instead it is getting served from the default /var/www/frontend/public directory.

server {
    listen 80;
    root /var/www/frontend/public;
    index index.php index.html index.htm;
    server_name demo-frontend.in;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location /dl {
        alias /var/www/frontend_react/build/;
        try_files $uri $uri/ /index.html?$args;


    }


    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php7.3-fpm.sock;
    }

}

Upvotes: 0

Views: 3864

Answers (1)

Holger Just
Holger Just

Reputation: 55833

The alias rules in nginx works in that the prefix defined in the location block (/dl in your case) is replaced with the argument (/var/www/frontend_react/build/ in your case).

nginx then applies the try_files arguments and attempts to find a suitable file to serve

For your given URL, this results in the following filesystem paths being checked:

/var/www/frontend_react/build//uurl/orr
/var/www/frontend_react/build//uurl/orr/

If no valid file was found at either of these locations, nginx performs an internal redirect to

 https://demo-frontend.in/index.html?

This internal redirect then matches your location / block and is thus served from there.

To fix this, you likely want to adjust your try_files directive to something like:

location /dl/ {
  alias /var/www/frontend_react/build/;
  try_files $uri $uri/index.html =404;
}

With that, nginx tried to find the the actual file first

/var/www/frontend_react/build/uurl/orr

and falls back to the index.html file if nothing servable was found

/var/www/frontend_react/build/uurl/orr/index.html

If that file still was not found, nginx then returns a 404 error.

Finally, please note that in my example, I have added a trailing slash to the location block. In your original example, you would be vulnerable to an arbitrary file read vulnerability which results in ANY file everywhere on your server to be readable by anyone with a URL such as

https://demo-frontend.in/dl../../../../etc/passwd

With alias rules, make sure to add a traling slash on either none or both of your paths.

Upvotes: 3

Related Questions