简体   繁体   中英

PHP 404 response and redirect

I know that I can setup a 404 error page simply enough using .htaccess.

As I understand it, if a page isn't found, an error gets sent back to the browser and the 404 page is displayed. The user may or may not be aware of this 'error'.

What I would like to do is allow the user to type in page1.php, page2.php, page3.php etc., and go to a page that prints page1, page2, page3, etc.. respectively.

The reasoning is that the logic is very similar for page1, page2, page3, etc.. I think it might be easier to send the user to the same page, which then calculates what to do using the PHP server variables: determine if this is a valid page or not, and then either throw a 404 error or print the correct message.

Is this possible? Or just a stupid thought?

I would like the url to be unaffected and remain as the user typed.

Thanks.

This is definitely not a stupid thought.

The instance that delivers content, or error pages if no content is found, is the web server. If you want to handle that logic in PHP, you can tell the web server to pass all requests to the same PHP file. Then you can make use of the $_SERVER variable to determine what the user was requesting and serve the content and send the correct status code (eg 404 ).

In Apache, you can define a Fallback Resource if you are using version 2.2.16 or later. This will redirect requests to non-existent files to a specified file.

<Directory /var/www/my_blog>
  FallbackResource index.php
</Directory>

In older Apache versions, you can use mod_rewrite to redirect the requests:

<Directory /var/www/my_blog>
  RewriteBase /my_blog

  RewriteCond /var/www/my_blog/%{REQUEST_FILENAME} !-f
  RewriteCond /var/www/my_blog/%{REQUEST_FILENAME} !-d
  RewriteRule ^ index.php [PT]
</Directory>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM