Nginx – configuration disallow files access

Author: Rafal Marguzewicz
Published:
Categories: NGINX
Tags:


Nginx disallow filesThis code allow access to files with only chosen extensions e.g : html|css|js|jpeg|jpg|png and disallow access to all the rest files:


location ~* ^.+\.(html|css|js|jpe?g||png)$ {
        try_files  $uri /$1?$args;
}

It is good idea for improvement security of our server. If you now which type files you need, you can choose and write in list regexp separated sign |

nginx restrict access to file PHP


 location ~ ^(.+\.php)$ {
      return 444;
 }

or


 location = /wp-admin/login.php {
      return 444;
 }

Full config example


server {
        server_name example.com;
        index index.php;
        include ssl.conf;
        root /path/to/localhost;

        location / {
                root /path/to/localhost/example.com/web;
                include fastcgi.conf;
                try_files  $uri /index.php?$args;
                
                location ~* ^/(.+\.(html|txt|css|js|jpg|jpeg|png|woff2?|woff|ttf|ico|pdf))$ {
                    try_files  $uri /$1?$args;
                }
        }

        location /blog {
                include fastcgi.conf;
                try_files  $uri /blog/index.php?$args;

                location ~* ^/blog/(.+\.(css|js|jpe?g|woff2?|ttf|png|gif|bmp|ico||pdf))$ {

                        try_files  $uri /blog/$1?$args;
                        access_log  off;
                        log_not_found  off;
                }

                location /blog/wp-admin {
                        try_files  $uri /blog/wp-admin/index.php?$args;
                        include fastcgi.conf;
                }
        }
}

Many interesting examples you find on github user perusio

Nginx – configuration disallow files access
5 / 1 vote


Your email address will not be published. Required fields are marked *

Name *
Email *

Read previous post:
Easy installation of Composer on Debian Linux

The first step of the installation are the same as on the site web of composer

Close