John Davidson

.htaccess stop directory listing and forward to handler.php

0 comments
Message:


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


My Answer:
You can prevent directory listing and forward all requests to your handler.php by adding the following lines to your .htaccess file:

apache
Options -Indexes

RewriteEngine On
RewriteBase /cms/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ my-handler.php?the_url=$1 [L,QSA]


This code will first disable directory listing with `Options -Indexes`, then it will check if the requested file or directory does not exist (`!-f` and `!-d` conditions) and rewrite the URL to my-handler.php with the requested URL as a parameter.

This way, even if you don't provide a slug, the request will be forwarded to my-handler.php for further processing.

Rate this post

4 of 5 based on 9533 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us