Nginx: Deny access of a directory and files inside it

14,827

Solution 1

Create another location block and see if it works:

    location ~ /admin/.*\.php$ {
       allow 192.168.0.0/24;
       deny all;

       include snippets/fastcgi-php.conf;
       fastcgi_pass unix:/var/run/php5-fpm.sock;
       fastcgi_split_path_info ^(.+\.php)(/.+)$;

       fastcgi_cache_bypass $skip_cache;
       fastcgi_no_cache $skip_cache;
       fastcgi_cache WORDPRESS;
       fastcgi_cache_valid 60m;
    }

Solution 2

server {
    location ^~ /vendor/ {
        deny all;
        return 403;
    }
    ...
}
Share:
14,827

Related videos on Youtube

hcheung
Author by

hcheung

//Code of the Day const status = feelBlessing; if ( isNew(knowledge) && bestDay === today() ) { learnItNow(); } else { display('Never too late to learn!'); }

Updated on September 16, 2022

Comments

  • hcheung
    hcheung over 1 year

    I have a directory /admin and I want to block the access of the directory and the files inside the directory whenever anyone access via public IP. Here is my setting:

    location /admin/ {
       allow 192.168.0.0/24;
       deny all;
    }
    

    This works fine when accessing the directory, however, if someone specifically access the file inside the directory (for example, url= "../admin/adminer.php), it doesn't deny the access of the file. I also tried other setting such as:

    location ~ /admin/.*$ {
           allow 192.168.0.0/24;
           deny all;
    }
    

    This seems to work in denying all the access when access from a public IP, however, the php code no longer work when accessing via internal IP, the php code simply echo out as plaintext.

    The rest of my location directives is provided here in case it somehow affect the behaviours:

    location / {
       try_files $uri $uri/ /index.php?args;
    }
    location ~ \.php$ {
      include snippets/fastcgi-php.conf;
      fastcgi_pass unix:/var/run/php5-fpm.sock;
      fastcgi_split_path_info ^(.+\.php)(/.+)$;
    
      fastcgi_cache_bypass $skip_cache;
      fastcgi_no_cache $skip_cache;
      fastcgi_cache WORDPRESS;
      fastcgi_cache_valid 60m;
    }
    

    Hope someone can help me to solve this.

  • hcheung
    hcheung over 7 years
    Thanks @alindt, I actually replace your location directive with my /admin location directive, and it works perfectly. I think I had the wrong regex expression on my code. I also took out the last four directives on cache as I don't want the /admin to be cached. Once again, thank you for the help.