Custom 404 error page — for PHP pages only

荒凉一梦 提交于 2019-11-27 22:30:53

问题


I have a personalized page for 404 with htaccess

ErrorDocument 404 /404.php

It works fine, but it takes everything .jpg, .js, .css etc...
I would like it to just take the .php and do a normal 404 error for all others.

I didn't find that option anywhere.

Thank you very much.


回答1:


Not sure but give this a try:

<Files ~ "\.php$">
    ErrorDocument 404 /404.php
</Files>

Quote from Files Directive documentation:

The <Files> directive limits the scope of the enclosed directives by filename.




回答2:


There are a few possible approaches to this, but I would do one of the following:

You can use mod_rewrite, as suggested by @LazyOne, to redirect only files with a .php extension to your custom document:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f # Only redirect to error for files that don't exist
RewriteRule ^(.*)\.php$ /404.php [L]

Or you can direct everything through the PHP error handler as you already do, and use PHP to determine whether the requested resource is a PHP script or not:

<?php

  if (strtolower(substr($_SERVER['SCRIPT_URL'], -4)) != '.php') {
    // If the requested resource does not have a .php extension, include the standard error doc and exit
    include '404.html';
    exit;
  }

  // Handle .php 404s here

The disadvantage of this second approach is that you may need to rewrite the standard error document so that it used PHP to get dynamic information to display to the user, such and the requested resource path.




回答3:


Utilizing the $_SERVER['REQUEST_URI'], you can easily check the ending of the file that resulted in an error and then throw a header to a normal 404 if it doesn't correspond to your needs or just render a different 404

Put this in your 404.php file

$bad_url = $_SERVER['REQUEST_URI'];
$bad_extension = substr(strrchr($bad_url,'.'),1);

if($bad_extension != "php"){
    //Not PHP
}else{
    //PHP
}


来源:https://stackoverflow.com/questions/9631496/custom-404-error-page-for-php-pages-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!