DanielGibbs
DanielGibbs

Reputation: 10173

Not allowing access to error page via URL using mod_rewrite

I have my custom error page at /errors/404.php and I would like that to be able to be used when apache can't find a file, but I would like it not able to be used by simply requesting the URL http://mywebsite/error/404.php.

I currently have a rule that blocks access to all of my php files (because I use URL rewriting to make user-friendly URLs) but this seems to also be stopping apache from reading the error page due to the error page matching the rule to deny access to php files.

How would I do this properly?

The contents of /.htaccess:

RewriteEngine On
RewriteRule ^home/?$       /index.php   [NC,L]
RewriteRule ^lessons/?$    /lessons.php [NC,L]

# Don't allow access to the actual php files.
RewriteCond %{THE_REQUEST} \.php[\ /?].*HTTP/ [NC]
RewriteRule ^.*$           -                  [R=404,L]

ErrorDocument 404 /errors/404.php

Upvotes: 0

Views: 314

Answers (1)

Felipe Alameda A
Felipe Alameda A

Reputation: 11799

You may try this instead:

# Don't allow access to the actual php files.
RewriteCond %{THE_REQUEST} \.php[\ /?].*HTTP/  [NC]
RewriteCond %{REQUEST_URI}  !/errors/404\.php  [NC]
RewriteRule ^.*$  -        [R=404,L]

RewriteCond %{THE_REQUEST} \s/errors/404\.php [NC]
RewriteRule .?  -  [F]

ErrorDocument 404 /errors/404.php
  1. All requests to .php files are redirected to /errors/404.php script.
  2. All requests to non-existent files or directories are redirected to /errors/404.php script (The ErrorDocument 404 /errors/404.php directive applies in this case).
  3. All direct requests to /errors/404.php return a 403 Forbidden status code.

Upvotes: 1

Related Questions