Search code examples
.htaccess

deny access to all files accept the index.php and the domain name with .htaccess


My website name is: cabinets.ga

I want to deny the access to all of my folders and files in my website, so this is my code to do that:

  Order deny,allow
  Deny from all
  <FilesMatch "index\.php">
  Allow from all
  </FilesMatch>

This code works fine if the user write the link with the index.php like that : cabinets.ga/index.php but if he write only the domain name without the index.php like that: cabinets.ga it will give him (Forbidden)

So i want that if he enter both the domain name with the index.php or without it the website display the index.php without Forbidden it.. Any help please?


Solution

  • You can actually just make the filename optional in the regex (you don't need to use mod_rewrite). For example:

    Order deny,allow
    Deny from all
    <FilesMatch "^(index\.php)?$">
        Allow from all
    </FilesMatch>
    

    This will allow direct requests to index.php and also requests for the directory (no filename) ...which results in index.php (the DirectoryIndex) being served by mod_dir via an internal subrequest (which occurs later).

    Note that you can't simply permit an empty filename (ie. "^$"). Whilst this allows the initial request for the bare directory, it will result in the internal subrequest for the DirectoryIndex, ie. index.php being blocked - so ultimately the request is blocked.

    Note also that this allows access to all index.php files in all subdirectories and all directories that contain an index.php index document.


    However, if you are on Apache 2.4 then you should be using Require instead, since Order, Deny and Allow are all deprecated on Apache 2.4.

    Require all denied
    <FilesMatch "^(index\.php)?$">
        Require all granted
    </FilesMatch>
    

    UPDATE: My website is a single page application has just an index.php page controls all of my website with jquery ajax request, so i want when the user writed any other links accept my domain name accept the domain name the htaccess will redirect the user to the domain name

    It sounds like you need to implement a front-controller pattern. The simplest form is using the FallbackResource directive. For example:

    FallbackResource /index.php
    

    Any requests that would otherwise result in a 404 are routed to /index.php. Any static resources (CSS, JS, images etc.) remain accessible and are not routed to /index.php.