Skip to content
Advertisement

.htaccess stop directory listing and forward to handler.php

I am trying to implement SEO friendly URLs using .htaccess and PHP. I have achieved 90% of my goal and struggling with just one use case.

Here is what happing, when I access the following url

http://somesite.com/cms/movies/tarzan

it lands on

my-handler.php?the_url=movies/tarzan

This is perfect and that is what I want because then I manage it myself. The real problem is when I don’t provide any slugs, then it lists the directory (means show all files and folders in it)

http://somesite.com/cms/

Can someone please help me fix following .htaccess content, so that even if I don’t provide slug it should still be handled by my-handler.php instead of lisiting full directory?

<IfModule mod_rewrite.c>
RewriteEngine On

RewriteBase /cms/
RewriteCond %{REQUEST_FILENAME} !/(admin|css|fonts|ico|include|js)/
RewriteRule ^my-handler.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /cms/my-handler.php?the_url=$1 [L,QSA]

</IfModule>

Solved

As per @Roman suggestion, I added the following to the above listing and it solved my problem. Plus I do not have to compromise on accessing physical directories RewriteCond %{REQUEST_FILENAME} !-d

DirectoryIndex my-handler.php

Advertisement

Answer

At first you have to set the DirectoryIndex to handle every request which points to / with your my-handler.php. This can be done by adding the line to your .htaccess

DirectoryIndex my-handler.php

To disable the directory listing, you have to forbid the listing by adding the following line to your .htaccess

Options -Indexes

Remember that this configuration is per .htaccess and just for the directory you are placing the file in. If you want to make changes for your whole webserver, you can edit the httpd.conf and search for

Options Indexes

and remove the Indexes option.

Documentation

The listing is provided by the mod_autoindex module.

Nice side-fact

If you just want to disable the listing of specific file-types like .env or .php files, you can add the option IndexIgnore *.php to you .htaccess

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement