简体   繁体   中英

Apache htaccess: Block direct access to index.html in a folder

I have the following code in my .htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On

    # block text, html and php files in the folder from being accessed directly
    RewriteRule ^content/(.*)\.(txt|html|php)$ error [R=301,L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d 
    RewriteRule . index.php [L]
</IfModule>

# Prevent file browsing
Options -Indexes

To block accessing txt, html, php files in the content folder. It works great and it blocks index.html if access the following URI

mysite.com/content/index.html

but it's not blocking the index.html content being displayed if it's omitted from URI like:

mysite.com/content/

How to solve this problem? Thank you.

You need to disable the directory index, not blocking anything. Just add this to your .htaccess file:

DirectoryIndex none.none
Options -Indexes

First line is to tell apache not to serve the "index.html" in case of a user navigates to the folder. More info at DirectoryIndex doc.

Second is to tell apache not to show the content of the folder, because there is no default file to show (First line disable it)

If you add DirectoryIndex none.none in the main directory .htaccess file you will disable the main index as well which might not be desired.

Your fix is:

RewriteRule ^content/?$ error [R=301,L]
RewriteRule ^content/(.*)\.(txt|html|php)$ error [R=301,L]

The above line tells Apache to redirect to error all requests to content and content/ as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM