Languages
[Edit]
EN

apache2 / .htaccess - run php script if file does not exist

9 points
Created by:
marc_so
1104

In this short article we would like to show you how configure .htaccess to execute some alernative script when file indicated in URL doesn't exist on apache2 server.

Quick solution (.htaccess file):

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ /script.php [L]

Β 

Web site details

Web site structure:

/var/www/html
          β”œβ”€β”€ .htaccess
          β”œβ”€β”€ file1.txt
          β”œβ”€β”€ file2.txt
          └── script.php

.htaccess file:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^.*$ /script.php [L]

file1.txt file:

file1.txt content ...
file1.txt content ...
file1.txt content ...

file2.txt file:

file2.txt content ...
file2.txt content ...
file2.txt content ...

script.php file:

<?php

	echo "Script executed ...";

?>

Screenshots:Β 

Some unexisting file on apache2 server - script.php executed instead.
Some unexisting file on apache2 server - script.php executed instead.
Existing file1.txt loaded - apache2 server.
Existing file1.txt loaded - apache2 server.
Existing file2.txt loaded - apache2 server.
Existing file2.txt loaded - apache2 server.
script.php executed as index.php - apache2 server.
script.php executed as index.php - apache2 server.

Β 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Apache2

Native Advertising
πŸš€
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

β€οΈπŸ’» πŸ™‚

Join