BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

How to prevent directory listing using htaccess

By Chaitanya Singh | Filed Under: WordPress

By default directory listing is enabled, which can compromise your website’s security. Enter a URL like this –

[code]http://yourwebsitename.com/wp-content/uploads/[/code]

When I entered this for my site, it redirected me to a 404 page, try this for your website if it is resulting the same then you are safe. Else it would return a complete directory structure, using which anyone can download all of your website’s pics in one go or even worse.

directory-listing-disabled-using-.htaccess-file

It is always safe to prevent directory listing. You can do it by simply adding a single line of code to your root .htaccess file. Add the below line at the end of .htaccess file –

[code]
Options All -Indexes
[/code]

If you are a WordPress user then the default content for your .htaccess file would be –

[code]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
[/code]

After adding the code to disable directory browsing your file would be-

[code]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Options All -Indexes[/code]

Another alternative
Similar to what above code does, there is another alternative statement, which prevents directory listing –

[code]
# Another solution for preventing directory browsing
IndexIgnore *
[/code]

What if you want to disable the directory listing only for few file types? For example you have couple of image files with .jpg & .jpeg extensions and you want to prevent listing only for these file types. You can do so by adding this piece of code –

[code]
# Would prevent listing for .jpeg & .png file types
IndexIgnore *.png *.jpeg
[/code]

Wanna enable directory listing?

[code]
# This code would enable directory listing -highly discouraged
Options All +Indexes
[/code]

There is another way to do it. You can change the default directory page by which you can redirect the user to your desired page upon entering the directory URLs. I will share about it in detail in another post.

Leave a Reply Cancel reply

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

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap