skip to Main Content

I was writing a .htaccess file for my PHP script.
This should only allow access to the index.php, cronjob.php and execute.php pages.
I wrote the .htaccess file as follows:

# Set default index file
DirectoryIndex index.php

# Disable indexing
Options -Indexes

# Set "403 Forbidden" as the default server behavior
Order Deny,Allow
Deny from all

# Allow requests to core PHP files
<FilesMatch "(index|execute|cronjob).php$">
    Allow from all
</FilesMatch>

# If mod_rewrite module exists...
<IfModule mod_rewrite.c>
    RewriteEngine On
    
    # ...restrict access to PHP private directories
    RewriteRule (^|/)logs(/|$) - [F]
    RewriteRule (^|/)utils(/|$) - [F]
    RewriteRule (^|/)modules(/|$) - [F]
</IfModule>

The main problem with this code is that https://example.com/ returns 403 Forbidden,
while https://example.com/index.php works.

2

Answers


  1. Chosen as BEST ANSWER

    In the end I managed to get it to work, I don't know if it's the best .htaccess possible, but this is what I ended up with:

    # Set default index file
    DirectoryIndex index.php
    
    # Disable indexing
    Options -Indexes
    
    # Set "403 Forbidden" as the default server behavior
    Order Deny,Allow
    Deny from all
    
    # Allow requests to core PHP files
    <FilesMatch "^((index|execute|cronjob).php)?$">  # Basically, it accepts the three PHP files and the empty string.
        Allow from all
    </FilesMatch>
    

  2. You could put condition to check if a URI is NOT having either index.php OR cronjob.php or execute.php then forbid that page so else other pages will be forbid apart from these 3 php uris.

    Please make sure you clear your browser cache before checking your URLs.

    RewriteEngine ON
    RewriteCond %{REQUEST_URI} !(index|cronjob|execute).php [NC]
    RewriteRule ^ - [F]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search