Search code examples
apache.htaccess

.htaccess file content to allow access to one file and one folder only


For the below files and folder structure

beta
   folder1
   folder2
   folder3
   file1.php
   file2.php

I need to restrict access to all files and folders with the exception of folder2 and file2.php. only.

My .htaccess file currently looks like this:

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REQUEST_URI} !/folder2%$
RewriteCond %{REQUEST_URI} !/file2.php
RewriteRule $ /beta/file2.php [R=302,L]

The above does work in one system, but not from other system.

Can you point out what i am doing wrong here?


Solution

  • Try changing your rules around so that you let the 2 folders pass through then redirect everything to file2:

    Options +FollowSymlinks
    RewriteEngine on
    RewriteBase /beta/
    RewriteRule ^file2\.php - [L]
    RewriteRule ^folder2 - [L]
    RewriteRule ^ file2.php [L,R=302]
    

    The error you were getting is probably from the % that you had in your condition.

    If you want to outright forbid access to anything else, you can change the last rule to:

    RewriteRule ^ - [L,F]
    

    If you dont mind can you please explain each line ?

    The RewriteBase directive lets the rewrite engine know that relative paths have a URI-base of /beta/. So all of the files/pathnames that don't start with a / will automatically have that base.

    The next two rules simply matches against the URI and does a "pass through" using the - character, which means, "don't do anything". So when you request /folder2 or /file2.php, the rewrite engine does nothing and lets the request through as if nothing happened. But if the request is anything else, the first 2 rules won't match and the last rule will match because the regex is ^, which matches everything. The target of that rule redirects everything to /beta/file2.php (because of the base).

    The forbidden rule with the F flag in the square brackets is the same thing, If the request isn't for the folder2 or file2.php, then that rule will match it (^) and it passes it through (-) but the F flag makes it return a "403 Forbidden" instead of serving whatever the request was for.