Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block access to files in a directory but allow index.html

Tags:

nginx

I'm hosting a website on /test/ but files can be accessed by going to the url if user knows filename. Ex:

domain.com/test/readmesample.txt

I have it setup like above but now when i go to domain.com/test the index.html file wont load and I get a 403 forbidden.

How can i set it up so when going to /test it allows the html file to load while still blocking files inside that directory? This includes files, folders and .files other than index.html.

location ~ /test {
             deny all;
}

Here is my config file

server {
listen 80;
listen 443 ssl default_server;

root /config/www;
index index.html index.htm index.php;

server_name www.domain.com;

ssl_certificate /config/keys/letsencrypt/fullchain.pem;
ssl_certificate_key /config/keys/letsencrypt/privkey.pem;
ssl_dhparam /config/nginx/dhparams.pem;
ssl_ciphers 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
ssl_prefer_server_ciphers on;

client_max_body_size 0;

location / {
    try_files $uri $uri/ /index.html /index.php?$args =404;

}

location ~ /new {
    deny all;

}       


location ~ \.php$ {
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    # With php5-cgi alone:
    fastcgi_pass 127.0.0.1:9000;
    # With php5-fpm:
    #fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    include /etc/nginx/fastcgi_params;
}

Thank you in advance

like image 983
jrdnlc Avatar asked Mar 02 '17 15:03

jrdnlc


People also ask

CAN index HTML be in a folder?

If you are using such a server, you can put your index. html in a folder. You see, where you should put your index. html is entirely dependent on the server implementation and how you set it up.

How do I block direct access in HTML?

You can define a variable like window. parentPage = true; in the index.


2 Answers

You can explicitly break out /test/index.html with:

location = /test/index.html {
}
location ^~ /test {
    deny all;
}

The exact match location has highest precedence, and the ^~ modifier places the precedence of the prefix location above regular expression locations at the same level.

See this document for more.

like image 187
Richard Smith Avatar answered Oct 20 '22 06:10

Richard Smith


I think I figured it out not sure if it's the proper way but it works. Feel free to correct me

location /test {
location ~ \.(txt|gif|jpg|png)$ {
      deny all;
      }
      } 

Using that blocks access to all those extensions in /test and inside any sub directory.

like image 22
jrdnlc Avatar answered Oct 20 '22 06:10

jrdnlc