How to prevent nginx from reverse proxy specific subdirectories

17,324

You can bind the proxy_pass to EXACTLY the path you like, like this

location = / {
    proxy_pass http://localhost:9999/;
}

This makes sure that no other path will be passed but /

OR

you can use this syntax for just the subdirectories to be matched

location ^~ /subdir {
     alias /var/www/site/subdir;
}

location / {
    proxy_pass http://localhost:9999/ ;
}

The ^~ matches the subdir and then stops searching so the / will not be executed. It is described here.

Share:
17,324

Related videos on Youtube

Falken
Author by

Falken

Updated on September 18, 2022

Comments

  • Falken
    Falken over 1 year

    On Apache you can ProxyPass everything except one or more subdirectories (with "!").

        ProxyPass /subdir !
        ProxyPass / http://localhost:9999/
    

    What is the Nginx equivalent ?

    My first guess is obviously not working :

     location /subdir {
          root /var/www/site/subdir;
      }
    
     location / {
          proxy_pass http://localhost:9999/ ;
      }
    
  • Tinus
    Tinus over 9 years
    root /var/www/site/subdir should be root /var/www/site in my case, otherwise nginx will try to access /var/www/site/subdir/subdir .
  • Christopher Perrin
    Christopher Perrin over 9 years
    You are right. Either that, or you can use alias instead of root
  • Mohammed Noureldin
    Mohammed Noureldin over 6 years
    Could you explain this ^~ more? I could not get what does it do. I tried reading the link you sent, but still cannot get it. If the longest matching prefix location has the “^~” modifier then regular expressions are not checked.
  • Christopher Perrin
    Christopher Perrin over 6 years
    @MohammedNoureldin it essentially means that it tries to match a prefix on a path and does not evaluate regular expressions.
  • Mohammed Noureldin
    Mohammed Noureldin over 6 years
    Actually my problem is with this word prefix: does it here mean the fix string (simple non-regex string)?
  • Christopher Perrin
    Christopher Perrin over 6 years
    @MohammedNoureldin it is the first part of the path that you want to use for the location. And yes it is without regex.