'.htaccess load index.php but not other .php files

I want to configure the .htaccess file to work the following way:

  1. If the visitor tries to open a url with an existing folder name, redirect to main page (index.html).

I have the following rules for that:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} !/index.html$ [NC]
    RewriteRule ^data/existing-folder-1$ https://example.com [R=301,NC,L]
    RewriteRule ^data/existing-folder-1/$ https://example.com [R=301,NC,L]
    RewriteRule ^data/existing-folder-2$ https://example.com [R=301,NC,L]
    RewriteRule ^data/existing-folder-2/$ https://example.com [R=301,NC,L]
</IfModule>

And it's working fine.

  1. If the user tries to open a forbidden type of file (like .php), send to 403.

     RewriteCond %{HTTP_REFERER} !^https://example.com [NC]
     RewriteRule \.(php|log|htaccess)$ - [F,L,NC]
    

And it's also working fine.

  1. I don't want users to see the contents of the folders, so I have this line: Options -Indexes

I think that's all the important details to see the background.

I have a /rd folder with a simple index.php file to redirect URLs:

$url=$_GET["url"];
if (empty($url)){
    //
} else {
    header("Location: " . $url, TRUE, 308);
    // later on with special functions
    exit();
}

Such a link on my page looks like this: https://example.com/rd/?url=https%3A%2F%2Ffoo-bar.com%2Fexample Please note, that index.php is not written after /rd/ and before ?url. But if it's easier to solve this issue, I can modify it.

And now the problem comes here:

  • When I click on such a link through my website, it works perfectly.
  • But when I copy this redirect-link, and try to open in a new tab/window, it says 403 Forbidden. I think because #2 rule to disable access to .php files outside my domain.

Since I want to share those redirect links, I want them to be able to open when copy-paste the links. I also don't want anyone to access any of my .php files - so it's not an option to remove rule #2.

How can I solve this issue? How can I enable to use the redirect links "alone", while keeping the rules to prevent access to files/folders?

Thank you.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source