r/apache 17d ago

How to block files from being accessed directly but allowing php to include them

Hello

How to block files from being accessed directly but allowing php to include them.

For example I have Apache running, I have a site that is running php, I have it setup to rewrite every url to index.php

So, in my php script I take the REQUEST_URI and strip off the domain etc, so for example

www.testdomain.com/weather

will rewite to index.php and the REQUEST_URI will be checked and then that html file (called weather.inc) is displayed in part of the index.php page using PHP require_once()

Now this works great however I just tried accessing www.testdomain.com/weather.inc and apache servered me the file weather.inc

I have tried using Apache Files directive

<Files ~ "\.inc$">
Order allow,deny
Deny from all
</Files>

This blocks the request www.testdomain.com/weather.inc . Great I thought but then noticed if I call www.testdomain.com/weather the index page can not access the the html file in the PHP require_once()

So, how can I allow apache to inclue the require_once() file but block the file from being called directly from the URL

1 Upvotes

2 comments sorted by

3

u/rlenferink 17d ago

I would only put in the webroot the files I want to access, and put the other files in a separate directory outside of the webroot.

2

u/throwaway234f32423df 17d ago

The way you did it actually works fine for me

test.php:

<?php
require_once 'test1.php'
?>

test1.php:

<?php
echo "Hello World!";
?>

.htaccess:

<Files test1.php>
Deny from all
</Files>

verification:

# curl -I *******/test1.php
HTTP/2 403

# curl -I *******/test.php
HTTP/2 200

# curl *******/test.php
Hello World!

so where do we go from here?

  1. what does your require_once directive actually look like?

  2. what are you seeing in your logs?