Ошибка 404 как вызвать

My file .htaccess handles all requests from /word_here to my internal endpoint /page.php?name=word_here. The PHP script then checks if the requested page is in its array of pages.

If not, how can I simulate an error 404?

I tried this, but it didn’t result in my 404 page configured via ErrorDocument in the .htaccess showing up.

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

Am I right in thinking that it’s wrong to redirect to my error 404 page?

Valerio Bozz's user avatar

asked Sep 4, 2009 at 19:29

Eric's user avatar

2

The up-to-date answer (as of PHP 5.4 or newer) for generating 404 pages is to use http_response_code:

<?php
http_response_code(404);
include('my_404.php'); // provide your own HTML for the error page
die();

die() is not strictly necessary, but it makes sure that you don’t continue the normal execution.

answered Jan 11, 2017 at 14:28

blade's user avatar

bladeblade

11.8k7 gold badges36 silver badges38 bronze badges

2

What you’re doing will work, and the browser will receive a 404 code. What it won’t do is display the «not found» page that you might be expecting, e.g.:

Not Found

The requested URL /test.php was not found on this server.

That’s because the web server doesn’t send that page when PHP returns a 404 code (at least Apache doesn’t). PHP is responsible for sending all its own output. So if you want a similar page, you’ll have to send the HTML yourself, e.g.:

<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
include("notFound.php");
?>

You could configure Apache to use the same page for its own 404 messages, by putting this in httpd.conf:

ErrorDocument 404 /notFound.php

Kzqai's user avatar

Kzqai

22.5k25 gold badges105 silver badges135 bronze badges

answered Sep 4, 2009 at 19:50

JW.'s user avatar

JW.JW.

50.5k36 gold badges114 silver badges142 bronze badges

3

Try this:

<?php
header("HTTP/1.0 404 Not Found");
?>

answered Sep 4, 2009 at 19:36

Ates Goral's user avatar

Ates GoralAtes Goral

137k26 gold badges137 silver badges190 bronze badges

2

Create custom error pages through .htaccess file

1. 404 — page not found

 RewriteEngine On
 ErrorDocument 404 /404.html

2. 500 — Internal Server Error

RewriteEngine On
ErrorDocument 500 /500.html

3. 403 — Forbidden

RewriteEngine On
ErrorDocument 403 /403.html

4. 400 — Bad request

RewriteEngine On
ErrorDocument 400 /400.html

5. 401 — Authorization Required

RewriteEngine On
ErrorDocument 401 /401.html

You can also redirect all error to single page. like

RewriteEngine On
ErrorDocument 404 /404.html
ErrorDocument 500 /404.html
ErrorDocument 403 /404.html
ErrorDocument 400 /404.html
ErrorDocument 401 /401.html

answered Mar 30, 2016 at 10:34

Irshad Khan's user avatar

Irshad KhanIrshad Khan

5,6202 gold badges43 silver badges39 bronze badges

1

Did you remember to die() after sending the header? The 404 header doesn’t automatically stop processing, so it may appear not to have done anything if there is further processing happening.

It’s not good to REDIRECT to your 404 page, but you can INCLUDE the content from it with no problem. That way, you have a page that properly sends a 404 status from the correct URL, but it also has your «what are you looking for?» page for the human reader.

answered Sep 4, 2009 at 19:50

Eli's user avatar

EliEli

97.1k20 gold badges76 silver badges81 bronze badges

Standard Apache 404 error looks like this:

<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
</body></html>  

Thus, you can use the following PHP code to generate 404 page that looks exactly as standard apache 404 page:

function httpNotFound()
{
    http_response_code(404);
    header('Content-type: text/html');

    // Generate standard apache 404 error page
    echo <<<HTML
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL was not found on this server.</p>
</body></html>  
HTML;

    exit;
}

answered Mar 20 at 16:14

Dima L.'s user avatar

Dima L.Dima L.

3,39332 silver badges30 bronze badges

try putting

ErrorDocument 404 /(root directory)/(error file) 

in .htaccess file.

Do this for any error but substitute 404 for your error.

StackedQ's user avatar

StackedQ

3,9791 gold badge27 silver badges41 bronze badges

answered May 20, 2018 at 19:41

the red crafteryt's user avatar

In the Drupal or WordPress CMS (and likely others), if you are trying to make some custom php code appear not to exist (unless some condition is met), the following works well by making the CMS’s 404 handler take over:

<?php
  if(condition){
    do stuff;
  } else {
    include('index.php');
  }
?>

answered Jan 28, 2019 at 19:38

Mike Godin's user avatar

Mike GodinMike Godin

3,6363 gold badges27 silver badges29 bronze badges

Immediately after that line try closing the response using exit or die()

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;

or

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
die();

answered May 25, 2018 at 4:22

user5891645's user avatar

4

try this once.

$wp_query->set_404();
status_header(404);
get_template_part('404'); 

Nikos Hidalgo's user avatar

answered Mar 31, 2020 at 4:24

Mani Kandan's user avatar

1

MaxxxNSK

header("HTTP/1.0 404 Not Found");
header("HTTP/1.1 404 Not Found");
header("Status: 404 Not Found");

— не работает


  • Вопрос задан

    более трёх лет назад

  • 12838 просмотров

В помощь Вам http-response-code(404) клац
писать до любого вывода

Пригласить эксперта

Ставьте error_reporting(-1); в начале кода и смотрите что не так.
Скорее всего перед header() был вывод данных.
А может вы что-то не так поняли? Ваш код всего-лишь объявляет, что данная страница — страница ошибки. Чтобы именно вызвать 404 попробуйте exit(header('Location: /error404/'));

Попробуйте добавить exit(); сразу после вызова header();

Так-же перед вызовом header(); у Вас не должно быть вывода информации, если первый вариант не помог, попробуйте убрать закрывающий PHP тег ?> (если он есть)

На самом деле Вы всего лишь отправили заголовок, чтобы показать страницу нужно взять include или заголовок location.


  • Показать ещё
    Загружается…

05 июн. 2023, в 15:13

2000 руб./в час

05 июн. 2023, в 15:02

7000 руб./за проект

05 июн. 2023, в 14:37

500 руб./за проект

Минуточку внимания

mjt at jpeto dot net

13 years ago


I strongly recommend, that you use

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

instead of

header("HTTP/1.1 404 Not Found");

I had big troubles with an Apache/2.0.59 (Unix) answering in HTTP/1.0 while I (accidentially) added a "HTTP/1.1 200 Ok" - Header.

Most of the pages were displayed correct, but on some of them apache added weird content to it:

A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser)

"0" at the bottom of the page (after the complete output of my php script)

It took me quite a while to find out about the wrong protocol in the HTTP-header.


Marcel G

13 years ago


Several times this one is asked on the net but an answer could not be found in the docs on php.net ...

If you want to redirect an user and tell him he will be redirected, e. g. "You will be redirected in about 5 secs. If not, click here." you cannot use header( 'Location: ...' ) as you can't sent any output before the headers are sent.

So, either you have to use the HTML meta refresh thingy or you use the following:

<?php

  header
( "refresh:5;url=wherever.php" );

  echo
'You'll be redirected in about 5 secs. If not, click <a href="wherever.php">here</a>.';

?>



Hth someone


Dylan at WeDefy dot com

15 years ago


A quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header().

<?php
// 301 Moved Permanently
header("Location: /foo.php",TRUE,301);// 302 Found
header("Location: /foo.php",TRUE,302);
header("Location: /foo.php");// 303 See Other
header("Location: /foo.php",TRUE,303);// 307 Temporary Redirect
header("Location: /foo.php",TRUE,307);
?>

The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it's a good idea to set the status code at the same time.  Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely.  Search engines typically transfer "page rank" to the new location for 301 redirects, but not for 302, 303 or 307. If the status code is not specified, header('Location:') defaults to 302.


mandor at mandor dot net

17 years ago


When using PHP to output an image, it won't be cached by the client so if you don't want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol.

Here's how:

<?php// Test image.
   
$fn = '/test/foo.png';// Getting headers sent by the client.
   
$headers = apache_request_headers(); // Checking if the client is validating his cache and if it is current.
   
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($fn))) {
       
// Client's cache IS current, so we just respond '304 Not Modified'.
       
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
    } else {
       
// Image not cached or cache outdated, we respond '200 OK' and output the image.
       
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
       
header('Content-Length: '.filesize($fn));
       
header('Content-Type: image/png');
        print
file_get_contents($fn);
    }
?>

That way foo.png will be properly cached by the client and you'll save bandwith. :)


php at ober-mail dot de

3 years ago


Since PHP 5.4, the function `http_​response_​code()` can be used to set the response code instead of using the `header()` function, which requires to also set the correct protocol version (which can lead to problems, as seen in other comments).

bebertjean at yahoo dot fr

14 years ago


If using the 'header' function for the downloading of files, especially if you're passing the filename as a variable, remember to surround the filename with double quotes, otherwise you'll have problems in Firefox as soon as there's a space in the filename.

So instead of typing:

<?php
  header
("Content-Disposition: attachment; filename=" . basename($filename));
?>

you should type:

<?php
  header
("Content-Disposition: attachment; filename="" . basename($filename) . """);
?>

If you don't do this then when the user clicks on the link for a file named "Example file with spaces.txt", then Firefox's Save As dialog box will give it the name "Example", and it will have no extension.

See the page called "Filenames_with_spaces_are_truncated_upon_download" at
http://kb.mozillazine.org/ for more information. (Sorry, the site won't let me post such a long link...)


tim at sharpwebdevelopment dot com

5 years ago


The header call can be misleading to novice php users.
when "header call" is stated, it refers the the top leftmost position of the file and not the "header()" function itself.
"<?php" opening tag must be placed before anything else, even whitespace.

yjf_victor

7 years ago


According to the RFC 6226 (https://tools.ietf.org/html/rfc6266), the only way to send Content-Disposition Header with encoding is:

Content-Disposition: attachment;
                          filename*= UTF-8''%e2%82%ac%20rates

for backward compatibility, what should be sent is:

Content-Disposition: attachment;
                          filename="EURO rates";
                          filename*=utf-8''%e2%82%ac%20rates

As a result, we should use

<?php
$filename
= '中文文件名.exe';   // a filename in Chinese characters$contentDispositionField = 'Content-Disposition: attachment; '
   
. sprintf('filename="%s"; ', rawurlencode($filename))
    .
sprintf("filename*=utf-8''%s", rawurlencode($filename));header('Content-Type: application/octet-stream');header($contentDispositionField);readfile('file_to_download.exe');
?>

I have tested the code in IE6-10, firefox and Chrome.


David Spector

1 year ago


Please note that there is no error checking for the header command, either in PHP, browsers, or Web Developer Tools.

If you use something like "header('text/javascript');" to set the MIME type for PHP response text (such as for echoed or Included data), you will get an undiagnosed failure.

The proper MIME-setting function is "header('Content-type: text/javascript');".


sk89q

14 years ago


You can use HTTP's etags and last modified dates to ensure that you're not sending the browser data it already has cached.

<?php

$last_modified_time
= filemtime($file);

$etag = md5_file($file);
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");

header("Etag: $etag");

if (@

strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||

   
trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {

   
header("HTTP/1.1 304 Not Modified");

    exit;

}

?>


nospam at nospam dot com

7 years ago


<?php// Response codes behaviors when using
header('Location: /target.php', true, $code) to forward user to another page:$code = 301;
// Use when the old page has been "permanently moved and any future requests should be sent to the target page instead. PageRank may be transferred."$code = 302; (default)
// "Temporary redirect so page is only cached if indicated by a Cache-Control or Expires header field."$code = 303;
// "This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource and is not cached."$code = 307;
// Beware that when used after a form is submitted using POST, it would carry over the posted values to the next page, such if target.php contains a form processing script, it will process the submitted info again!

// In other words, use 301 if permanent, 302 if temporary, and 303 if a results page from a submitted form.
// Maybe use 307 if a form processing script has moved.

?>

ben at indietorrent dot org

11 years ago


Be aware that sending binary files to the user-agent (browser) over an encrypted connection (SSL/TLS) will fail in IE (Internet Explorer) versions 5, 6, 7, and 8 if any of the following headers is included:

Cache-control:no-store
Cache-control:no-cache

See: http://support.microsoft.com/kb/323308

Workaround: do not send those headers.

Also, be aware that IE versions 5, 6, 7, and 8 double-compress already-compressed files and do not reverse the process correctly, so ZIP files and similar are corrupted on download.

Workaround: disable compression (beyond text/html) for these particular versions of IE, e.g., using Apache's "BrowserMatch" directive. The following example disables compression in all versions of IE:

BrowserMatch ".*MSIE.*" gzip-only-text/html


David

5 years ago


It seems the note saying the URI must be absolute is obsolete. Found on https://en.wikipedia.org/wiki/HTTP_location

«An obsolete version of the HTTP 1.1 specifications (IETF RFC 2616) required a complete absolute URI for redirection.[2] The IETF HTTP working group found that the most popular web browsers tolerate the passing of a relative URL[3] and, consequently, the updated HTTP 1.1 specifications (IETF RFC 7231) relaxed the original constraint, allowing the use of relative URLs in Location headers.»


chris at ocproducts dot com

6 years ago


Note that 'session_start' may overwrite your custom cache headers.
To remedy this you need to call:

session_cache_limiter('');

...after you set your custom cache headers. It will tell the PHP session code to not do any cache header changes of its own.


shutout2730 at yahoo dot com

14 years ago


It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.

This redirects to 2.html since the second header replaces the first.

<?php
header
("location: 1.html");
header("location: 2.html"); //replaces 1.html
?>

This redirects to 1.html since the header is sent as soon as the echo happens. You also won't see any "headers already sent" errors because the browser follows the redirect before it can display the error.

<?php
header
("location: 1.html");
echo
"send data";
header("location: 2.html"); //1.html already sent
?>

Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren't sent until the output buffer is flushed.

<?php
ob_start
();
header("location: 1.html");
echo
"send data";
header("location: 2.html"); //replaces 1.html
ob_end_flush(); //now the headers are sent
?>


jp at webgraphe dot com

19 years ago


A call to session_write_close() before the statement

<?php

    header
("Location: URL");

    exit();

?>



is recommended if you want to be sure the session is updated before proceeding to the redirection.

We encountered a situation where the script accessed by the redirection wasn't loading the session correctly because the precedent script hadn't the time to update it (we used a database handler).

JP.


dev at omikrosys dot com

13 years ago


Just to inform you all, do not get confused between Content-Transfer-Encoding and Content-Encoding

Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).
Eg Use:- header('Content-Transfer-Encoding: binary');

Content-Encoding is used to apply things like gzip compression to the content/data.
Eg Use:- header('Content-Encoding: gzip');


Angelica Perduta

3 years ago


I made a script that generates an optimized image for use on web pages using a 404 script to resize and reduce original images, but on some servers it was generating the image but then not using it due to some kind of cache somewhere of the 404 status. I managed to get it to work with the following and although I don't quite understand it, I hope my posting here does help others with similar issues:

    header_remove();
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    // ... and then try redirecting
    // 201 = The request has been fulfilled, resulting in the creation of a new resource however it's still not loading
    // 302 "moved temporarily" does seems to load it!
    header("location:$dst", FALSE, 302); // redirect to the file now we have it


mzheng[no-spam-thx] at ariba dot com

14 years ago


For large files (100+ MBs), I found that it is essential to flush the file content ASAP, otherwise the download dialog doesn't show until a long time or never.

<?php
header
("Content-Disposition: attachment; filename=" . urlencode($file));   
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");            
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.$fp = fopen($file, "r");
while (!
feof($fp))
{
    echo
fread($fp, 65536);
   
flush(); // this is essential for large downloads

fclose($fp);
?>


razvan_bc at yahoo dot com

5 years ago


<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>

this example is pretty good BUT in time you use "exit" the parser will still work to decide what's happening next the "exit" 's action should do ('cause if you check the manual exit works in others situations too).
SO MY POINT IS : you should use :
<?php

header

('Location: http://www.example.com/');
die();
?>
'CAUSE all die function does is to stop the script ,there is no other place for interpretation and the scope you choose to break the action of your script is quickly DONE!!!

there are many situations  with others examples and the right choose for small parts of your scrips that make differences when you write your php framework at well!

Thanks Rasmus Lerdorf and his team to wrap off parts of unusual php functionality ,php 7 roolez!!!!!


scott at lucentminds dot com

13 years ago


If you want to remove a header and keep it from being sent as part of the header response, just provide nothing as the header value after the header name. For example...

PHP, by default, always returns the following header:

"Content-Type: text/html"

Which your entire header response will look like

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Content-Type: text/html; charset=UTF-8
Connection: close

If you call the header name with no value like so...

<?php

    header

( 'Content-Type:' );?>

Your headers now look like this:

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Connection: close


Vinay Kotekar

8 years ago


Saving php file in ANSI  no isuess but when saving the file in UTF-8 format for various reasons remember to save the file without any BOM ( byte-order mark) support.
Otherwise you will face problem of headers not being properly sent
eg.
<?php header("Set-Cookie: name=user");?>

Would give something like this :-

Warning: Cannot modify header information - headers already sent by (output started at C:wwwinfo.php:1) in C:wwwinfo.php on line 1


Cody G.

12 years ago


After lots of research and testing, I'd like to share my findings about my problems with Internet Explorer and file downloads.

  Take a look at this code, which replicates the normal download of a Javascript:

<?php
if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
 
header("Content-type: text/javascript");
 
header("Content-Disposition: inline; filename="download.js"");
 
header("Content-Length: ".filesize("my-file.js"));
} else {
 
header("Content-type: application/force-download");
 
header("Content-Disposition: attachment; filename="download.js"");
 
header("Content-Length: ".filesize("my-file.js"));
}
header("Expires: Fri, 01 Jan 2010 05:00:00 GMT");
if(
strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
 
header("Cache-Control: no-cache");
 
header("Pragma: no-cache");
}
include(
"my-file.js");
?>

Now let me explain:

  I start out by checking for IE, then if not IE, I set Content-type (case-sensitive) to JS and set Content-Disposition (every header is case-sensitive from now on) to inline, because most browsers outside of IE like to display JS inline. (User may change settings). The Content-Length header is required by some browsers to activate download box. Then, if it is IE, the "application/force-download" Content-type is sometimes required to show the download box. Use this if you don't want your PDF to display in the browser (in IE). I use it here to make sure the box opens. Anyway, I set the Content-Disposition to attachment because I already know that the box will appear. Then I have the Content-Length again.

  Now, here's my big point. I have the Cache-Control and Pragma headers sent only if not IE. THESE HEADERS WILL PREVENT DOWNLOAD ON IE!!! Only use the Expires header, after all, it will require the file to be downloaded again the next time. This is not a bug! IE stores downloads in the Temporary Internet Files folder until the download is complete. I know this because once I downloaded a huge file to My Documents, but the Download Dialog box put it in the Temp folder and moved it at the end. Just think about it. If IE requires the file to be downloaded to the Temp folder, setting the Cache-Control and Pragma headers will cause an error!

I hope this saves someone some time!
~Cody G.


Refugnic

13 years ago


My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file.

After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to 'Always perform this operation with this file type'.

As I found out, the problem was in the header directive 'Content-Disposition', namely the 'attachment' directive.

If you want your browser to simulate a plain link to a file, either change 'attachment' to 'inline' or omit it alltogether and you'll be fine.

This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem.


Anonymous

13 years ago


I just want to add, becuase I see here lots of wrong formated headers.

1. All used headers have first letters uppercase, so you MUST follow this. For example:

Location, not location

Content-Type, not content-type, nor CONTENT-TYPE

2. Then there MUST be colon and space, like

good: header("Content-Type: text/plain");

wrong: header("Content-Type:text/plain");

3. Location header MUST be absolute uri with scheme, domain, port, path, etc.

good: header("Location: http://www.example.com/something.php?a=1");

4. Relative URIs are NOT allowed

wrong:  Location: /something.php?a=1

wrong:  Location: ?a=1

It will make proxy server and http clients happier.


bMindful at fleetingiamge dot org

20 years ago


If you haven't used, HTTP Response 204 can be very convenient. 204 tells the server to immediately termiante this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.

     header("status: 204");  (or the other call)

     header("HTTP/1.0 204 No Response");


nobileelpirata at hotmail dot com

16 years ago


This is the Headers to force a browser to use fresh content (no caching) in HTTP/1.0 and HTTP/1.1:

<?PHP

header
( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' );

header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );

header( 'Cache-Control: no-store, no-cache, must-revalidate' );

header( 'Cache-Control: post-check=0, pre-check=0', false );

header( 'Pragma: no-cache' );
?>


jamie

14 years ago


The encoding of a file is discovered by the Content-Type, either in the HTML meta tag or as part of the HTTP header. Thus, the server and browser does not need - nor expect - a Unicode file to begin with a BOM mark. BOMs can confuse *nix systems too. More info at http://unicode.org/faq/utf_bom.html#bom1

On another note: Safari can display CMYK images (at least the OS X version, because it uses the services of QuickTime)


er dot ellison dot nyc at gmail dot com

7 years ago


DO NOT PUT space between location and the colon that comes after that ,
// DO NOT USE THIS :
header("Location : #whatever"); // -> will not work !

// INSTEAD USE THIS ->
header("Location: #wahtever"); // -> will work forever !


ASchmidt at Anamera dot net

5 years ago


Setting the "Location: " header has another undocumented side-effect!

It will also disregard any expressly set "Content-Type: " and forces:

"Content-Type: text/html; charset=UTF-8"

The HTTP RFCs don't call for such a drastic action. They simply state that a redirect content SHOULD include a link to the destination page (in which case ANY HTML compatible content type would do). But PHP even overrides a perfectly standards-compliant
"Content-Type: application/xhtml+xml"!


hamza dot eljaouhari dot etudes at gmail dot com

4 years ago


// Beware that adding a space between the keyword "Location" and the colon causes an Internal Sever Error

//This line causes the error
        7
header('Location : index.php&controller=produit&action=index');

// While It must be written without the space
header('Location: index.php&controller=produit&action=index');


cedric at gn dot apc dot org

12 years ago


Setting a Location header "returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set".  If you are sending a response to a POST request, you might want to look at RFC 2616 sections 10.3.3 and 10.3.4.   It is suggested that if you want the browser to immediately GET the resource in the Location header in this circumstance, you should use a 303 status code not the 302 (with the same link as hypertext in the body for very old browsers).  This may have (rare) consequences as mentioned in bug 42969.

In this tutorial, we are going to show you how to send a “404 Not Found” header using PHP.

This can be especially useful in cases when you need to display a 404 message if a particular database record does not exist.

By sending a 404 HTTP status code to the client, we can tell search engines and other crawlers that the resource does not exist.

To send a 404 to the client, we can use PHP’s http_response_code function like so.

//Send 404 response to client.
http_response_code(404)
//Include custom 404.php message
include 'error/404.php';
//Kill the script.
exit;

Note that this function is only available in PHP version 5.4 and after.

If you are using a PHP version that is older than 5.4, then you will need to use the header function instead.

//Use header function to send a 404
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
//Include custom message.
include 'errors/404.php';
//End the script
exit;

In the code above, we.

  1. Send the response code to the client.
  2. We include a PHP file that contains our custom “404 Not Found” error. This file is not mandatory, so feel free to remove it if you want to.
  3. We then terminated the PHP script by calling the exit statement.

If you run one of the code samples above and check the response in your browser’s developer tools, then you will see something like this.

Request URL:http://localhost/test.php
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:80
Referrer Policy:no-referrer-when-downgrade

Note the Status Code segment of the server’s HTTP response. This is the 404 header.

When should I use this?

In most cases, your web server will automatically handle 404 errors if a resource does not exist.

However, what happens if your script is dynamic and it selects data from your database? What if you have a dynamic page such as users.php?id=234 and user 234 does not exist?

The file users.php will exist, so your web server will send back a status of “200 OK”, regardless of whether a user with the ID 234 exists or not.

In cases like this, we may need to manually send a 404 Not Found header.

Why isn’t PHP showing the same 404 message as my web server?

You might notice that your web server does not serve its default “404 Not Found” error message when you manually send the header with PHP.

404 Not Found

The default message that Apache displays whenever a resource could not be found.

This is because, as far as the web server is concerned, the file does exist and it has already done its job.

One solution to this problem is to make sure that PHP and your web server display the exact same 404 message.

For example, with Apache, you can specify the path of a custom error message by using the ErrorDocument directive.

ErrorDocument 404 /errors/404.php

The Nginx web server also allows you to configure custom error messages.

Ошибка 404Я решил перенести большую часть файлов со старого сайта на новый. И у меня возник вопрос — «А не обвинит ли меня Yandex в использовании неуникальных статей?», т.к. у меня одни и те же материалы будут на разных страницах.

Я написал письмо в службу поддержки yandex, и мне пришло письмо, в котором сообщалось, что переживать не надо. Единственно, настоятельно желательно, чтобы я каким-то способом закрыл старые странички от индексирования (через robots.txt, вызов ошибки 404 или перенаправление) и удалил странички из базы по адресу http://webmaster.yandex.ru/delurl.xml. Удалять по указанному адресу желательно, чтобы быстрее прекратилась индексация страниц.

По некоторым причинам я предпочел способ вызова ошибки 404. Ошибка 404 вызывается в том случае, если ресурс на который идет ссылка не обнаружен. И тут я обнаружил, что у меня то и нет вызова этой ошибки, т.е. какие бы данные пользователь не ввел бы на старом сайте, что-то все равно выводится. Такая ситуация на мой взгляд не допустима, и я пошел с ней бороться.

Мой сайт написан был на php, поэтому я очень быстро нашел команду для вызова ошибки 404. Она имеет вид:

header("HTTP/1.0 404 Not Found");
exit;

Казалось бы все просто, но нет же. Никак эти две команды не хотели работать. Тогда я почитал дополнительно материал и выяснил, что  header() должна вызываться до отправки любого другого вывода. Т.е. она должна быть исключительно самой первой при выводе, поэтому ее нельзя использовать внутри require_once().

Но как оказалось существуют три замечательные функции, которые позволяют решить эту проблему:

  • ob_start() — задает начало области, которую надо поместить в буфер, я поместил ее самой первой при выводе.

  • ob_end_flush() — окончание задания буфер и сразу вывод. Т.е. первые две функции задают область, которую сначала нужно вывести в буфер, а потом сразу вывести.
  • ob_end_clean() — очищает буфер, и следующая команда как бы выводится самой первой.

С использованием этих команд организация вызова ошибки 404 выглядит следующим образом:

  1. Самая первая команда — ob_start()
  2. Далее идет основное содержание, которое пока копируется в буфер.
  3. Проверка на предмет вызова ошибки 404. Например, проверка наличия определенного значения. Если после проверки имеются причины вызвать ошибку, то задается код:
    ob_end_clean() ;
    header("HTTP/1.0 404 Not Found");
    exit;

    Тем самым будет выдано сообщение об ошибке и осуществлен выход.

  4. Выводим содержимое буфера командой ob_end_flush(). Идея в том, что если была вызвана ошибка, то сюда не попадем. Если ошибки не было, то выводим буфер.

Далее в файле .htaccess можно указать файл, который будет сопоставляться ошибке 404, но это уже совершенно другая история…

MaxxxNSK

header("HTTP/1.0 404 Not Found");
header("HTTP/1.1 404 Not Found");
header("Status: 404 Not Found");

— не работает


  • Вопрос задан

    более трёх лет назад

  • 11564 просмотра

В помощь Вам http-response-code(404) клац
писать до любого вывода

Пригласить эксперта

Ставьте error_reporting(-1); в начале кода и смотрите что не так.
Скорее всего перед header() был вывод данных.
А может вы что-то не так поняли? Ваш код всего-лишь объявляет, что данная страница — страница ошибки. Чтобы именно вызвать 404 попробуйте exit(header('Location: /error404/'));

Попробуйте добавить exit(); сразу после вызова header();

Так-же перед вызовом header(); у Вас не должно быть вывода информации, если первый вариант не помог, попробуйте убрать закрывающий PHP тег ?> (если он есть)

На самом деле Вы всего лишь отправили заголовок, чтобы показать страницу нужно взять include или заголовок location.


  • Показать ещё
    Загружается…

29 янв. 2023, в 10:09

2000 руб./за проект

28 янв. 2023, в 13:14

10000 руб./за проект

29 янв. 2023, в 03:07

300000 руб./за проект

Минуточку внимания

My file .htaccess handles all requests from /word_here to my internal endpoint /page.php?name=word_here. The PHP script then checks if the requested page is in its array of pages.

If not, how can I simulate an error 404?

I tried this, but it didn’t result in my 404 page configured via ErrorDocument in the .htaccess showing up.

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

Am I right in thinking that it’s wrong to redirect to my error 404 page?

Valerio Bozz's user avatar

asked Sep 4, 2009 at 19:29

Eric's user avatar

2

The up-to-date answer (as of PHP 5.4 or newer) for generating 404 pages is to use http_response_code:

<?php
http_response_code(404);
include('my_404.php'); // provide your own HTML for the error page
die();

die() is not strictly necessary, but it makes sure that you don’t continue the normal execution.

answered Jan 11, 2017 at 14:28

blade's user avatar

bladeblade

11.3k7 gold badges36 silver badges37 bronze badges

2

What you’re doing will work, and the browser will receive a 404 code. What it won’t do is display the «not found» page that you might be expecting, e.g.:

Not Found

The requested URL /test.php was not found on this server.

That’s because the web server doesn’t send that page when PHP returns a 404 code (at least Apache doesn’t). PHP is responsible for sending all its own output. So if you want a similar page, you’ll have to send the HTML yourself, e.g.:

<?php
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404);
include("notFound.php");
?>

You could configure Apache to use the same page for its own 404 messages, by putting this in httpd.conf:

ErrorDocument 404 /notFound.php

Kzqai's user avatar

Kzqai

22.4k24 gold badges104 silver badges134 bronze badges

answered Sep 4, 2009 at 19:50

JW.'s user avatar

JW.JW.

50.1k36 gold badges114 silver badges141 bronze badges

3

Try this:

<?php
header("HTTP/1.0 404 Not Found");
?>

answered Sep 4, 2009 at 19:36

Ates Goral's user avatar

Ates GoralAtes Goral

136k26 gold badges135 silver badges190 bronze badges

2

Create custom error pages through .htaccess file

1. 404 — page not found

 RewriteEngine On
 ErrorDocument 404 /404.html

2. 500 — Internal Server Error

RewriteEngine On
ErrorDocument 500 /500.html

3. 403 — Forbidden

RewriteEngine On
ErrorDocument 403 /403.html

4. 400 — Bad request

RewriteEngine On
ErrorDocument 400 /400.html

5. 401 — Authorization Required

RewriteEngine On
ErrorDocument 401 /401.html

You can also redirect all error to single page. like

RewriteEngine On
ErrorDocument 404 /404.html
ErrorDocument 500 /404.html
ErrorDocument 403 /404.html
ErrorDocument 400 /404.html
ErrorDocument 401 /401.html

answered Mar 30, 2016 at 10:34

Irshad Khan's user avatar

Irshad KhanIrshad Khan

5,5162 gold badges42 silver badges39 bronze badges

1

Did you remember to die() after sending the header? The 404 header doesn’t automatically stop processing, so it may appear not to have done anything if there is further processing happening.

It’s not good to REDIRECT to your 404 page, but you can INCLUDE the content from it with no problem. That way, you have a page that properly sends a 404 status from the correct URL, but it also has your «what are you looking for?» page for the human reader.

answered Sep 4, 2009 at 19:50

Eli's user avatar

EliEli

96.3k20 gold badges75 silver badges81 bronze badges

try putting

ErrorDocument 404 /(root directory)/(error file) 

in .htaccess file.

Do this for any error but substitute 404 for your error.

StackedQ's user avatar

StackedQ

3,9011 gold badge27 silver badges41 bronze badges

answered May 20, 2018 at 19:41

the red crafteryt's user avatar

In the Drupal or WordPress CMS (and likely others), if you are trying to make some custom php code appear not to exist (unless some condition is met), the following works well by making the CMS’s 404 handler take over:

<?php
  if(condition){
    do stuff;
  } else {
    include('index.php');
  }
?>

answered Jan 28, 2019 at 19:38

Mike Godin's user avatar

Mike GodinMike Godin

3,5663 gold badges27 silver badges29 bronze badges

Immediately after that line try closing the response using exit or die()

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
exit;

or

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
die();

answered May 25, 2018 at 4:22

user5891645's user avatar

4

try this once.

$wp_query->set_404();
status_header(404);
get_template_part('404'); 

Nikos Hidalgo's user avatar

answered Mar 31, 2020 at 4:24

Mani Kandan's user avatar

1

Посетители сайта видят 404 ошибку, если страница, на которую они пытаются перейти, не существует или по какой-то причине сервер не может её найти. В статье рассмотрим, что это за ошибка и какое влияние она оказывает на поведенческие факторы пользователей и SEO. А также разберем, как настроить редирект 404 ошибки через .htaccess.

Ошибка 404 (File not found) возникает, когда сервер не может найти запрашиваемую пользователем страницу. От ее появления не застрахован ни один сайт. Достаточно ввести в адресной строке после домена рандомный набор символов. Например:

http://site.ru/asdfjkl;

Сервер не сможет найти страницу, и отобразится ошибка:



редирект 404 1
Ошибка 404 на сайте reg.ru

Также с ошибкой 404 можно столкнуться в следующих случаях:

  • Администратор сайта удалил или переместил страницу, но не сделал редирект на актуальный материал.
  • Изменилась структура сайта, а у страниц остались старые URL.
  • Посетитель опечатался в адресе, когда вводил его вручную.
  • Посетитель перешел по «битой» ссылке, которая ведет на несуществующую (удаленную или перемещенную) страницу.

Технически ошибка 404 связана с тем, что при открытии страницы браузер пользователя отправляет серверу запрос на контент, а сервер не находит запрашиваемой страницы и возвращает соответствующий ответ: не найдено.

Код 404 не стоит путать с другими похожими ошибками. Например, 403-й, которая означает, что доступ к ресурсу ограничен или запрещен. Подробнее о том, как ее исправить в статье.

Иногда при загрузке несуществующей страницы браузер получает ответ 200 вместо 404. Такой случай называют Ложной ошибкой (Soft 404). Он означает, что со страницей всё в порядке, хотя пользователь видит ошибку. Также проблема заключается в том, что Яндекс и Google показывают эту страницу в результатах поиска. Чтобы проверить код ошибки, воспользуйтесь проверкой URL от Google.

Наличие ложных ошибок негативно сказывается на SEO-продвижении и затрудняет видимость основного контента сайта. Чтобы это исправить, нужно вручную настроить редирект на страницу с ошибкой 404 для всех несуществующих страниц.

Возможные последствия для сайта

В самом наличии ошибок 404 на сайте нет ничего страшного. Как уже говорилось выше, посетитель может просто опечататься в адресе. Однако разработчику сайта стоит уделить внимание созданию и отладке страницы ошибки 404. О том, как это сделать, мы расскажем ниже.

Также важно следить за тем, чтобы на сайте было как можно меньше несуществующих страниц, битых ссылок и т. п. Чтобы отыскать их, можно воспользоваться веб-инструментами Яндекс и Google или другими сервисами. Найдите все, что нужно поправить, настройте 301-й редирект на актуальные материалы и замените некорректные ссылки.

Если на сайте регулярно встречается ошибка 404, это может повлиять на поведение посетителей. Пользователи, которые многократно видят сообщение о том, что страница не существует/не найдена, с большой вероятностью покинут сайт и уйдут к конкурентам.

Рекомендации по созданию страницы 404

Если сайт создавался в CMS WordPress, Joomla, Drupal и т. п., в нем, скорее всего, предусмотрена страница ошибки 404. Но она может быть неинформативной или отличаться от дизайна остальных страниц вашего веб-ресурса.

Лучше всего — создать свою страницу для ошибки 404. Если вы владеете навыками верстки и дизайна, можно сделать эту страницу красивой, шуточной и необычной. Это хорошо воспринимается пользователями и снижает негативный эффект.

Важно, чтобы страница была информативной и полезной:

  • Объясните, что случилось и почему пользователю попалась ошибка;
  • Посоветуйте, что пользователю стоит сделать, чтобы найти интересующий его контент;
  • Оставьте каналы для связи и возможность связаться с поддержкой сайта.

Яндекс рекомендует оформлять страницу ошибки 404 так, чтобы она отличалась от остальных страниц сайта и содержала ссылку на главную страницу, поисковую строку и инструкцию с дальнейшими действиями.

Примеры страниц с ошибкой 404



редирект 404 2
СберМаркет предлагает познать мудрость котов и цены на сайте



редирект 404 3
404 ошибка в разделе «Помощь» на сайте REG.RU

Как создать страницу ошибки 404 и настроить редирект на нее в .htaccess

  1. 1.

    Создайте страницу одним из следующих способов:

    • Если вы знаете HTML и CSS, напишите код страницы самостоятельно и загрузите файл с названием 404.html в корневую папку сайта.

    • Если навыков верстки нет, в интернете можно найти бесплатные шаблоны со страницами ошибки. Скачайте файл и добавьте его в корневую папку.

    • Если вы используете WordPress, воспользуйтесь плагином 404page — your smart custom 404 error page по инструкции ниже. Обратите внимание! Если вы воспользовались плагином, вам не нужно прописывать путь к файлу в .htaccess.


    Как настроить страницу в плагине WordPress

    1) Откройте админку вашего сайта в WordPress.

    2) Перейдите в раздел «Плагины» и нажмите Добавить новый.

    3) В строке поиска введите название 404page — your smart custom 404 error page.

    4) Нажмите УстановитьАктивировать:



    редирект 404 4

    5) Перейдите в раздел Внешний вид404 Error Page.

    6) Выберите в списке Sample Page, чтобы сменить стандартную страницу ошибки, и нажмите Edit Page:



    редирект 404 5

    7) Создайте страницу в открывшемся визуальном редакторе и нажмите Обновить:



    редирект 404 6

    Готово! После обновления страница будет использоваться автоматически.

  2. 2.

    Откройте конфигурационный файл .htaccess в корневой папке вашего сайта и добавьте в него строку:

    ErrorDocument 404 https://site.ru/404.html

    Где вместо site.ru — домен вашего сайта.

  3. 3.

    Сохраните изменения.

Готово! Теперь при возникновении 404 ошибки, в браузере пользователей будет открываться созданная вами кастомная страница.

Также рекомендуется закрыть служебную страницу 404 от индексации, чтобы она не возникала в поисковой выдаче вместе с остальными страницами сайта. Для этого откройте файл robots.txt в корневой папке сайта, добавьте соответствующую команду и сохраните изменения:

Редирект с 404 на главную (не рекомендуется)

Чтобы не создавать отдельную страницу ошибки 404, некоторые веб-разработчики прописывают в .htaccess редирект на главную страницу сайта. Это нежелательно делать с точки зрения SEO-оптимизации.

Также редирект на главную страницу может ввести пользователей в заблуждение. Представьте, что вместо искомой страницы у посетителя открывается главный экран сайта. Будет непонятно, почему это произошло, ведь пользователь искал какой-то конкретный контент и не узнает, что не сможет найти его.

Рекомендуется использовать специальные страницы для ошибки 404.

Проверка редиректа 404

Проверить, корректно ли все настроено можно в Яндекс.Вебмастер и Google Search Console.

Яндекс.Вебмастер

Если вы используете его впервые, укажите домен вашего сайта и пройдите проверку валидации, добавив файл в корневую папку сайта. Это займет несколько минут.

  1. 1.
  2. 2.

    Перейдите в раздел ИнструментыПроверка ответа сервера.

  3. 3.

    Введите название страницы ошибки и нажмите Проверить.

  4. 4.

    В коде статуса HTTP должно отображаться 404 Not Found:



    редирект 404 7

Google Search Console

Если вы используете этот инструмент впервые, укажите свой домен и пройдите валидацию, добавив TXT-запись/загрузив файл в корневую папку сайта или с помощью других способов.

  1. 1.
  2. 2.

    Перейдите в раздел «Покрытие» в меню справа. Здесь будет отображаться информация о страницах ошибок.

На сайте небольшого объема можно самостоятельно следить за наличием ошибок и постараться не допускать того, чтобы на нём было много страниц, утративших актуальность. Своевременно настраивайте 301 редиректы, когда статья в справке, страница или товар теряют актуальность.

Если сайт многораздельный и многостраничный, вручную мониторить его будет сложно. Рекомендуется использовать для поиска страниц ошибки 404 онлайн-сервисы (Serpstat, BadLincs.ru и другие). Также можно воспользоваться плагинами в CMS. Замените ссылки и настройте редиректы. А также создайте понятную красочную страницу ошибки с объяснением причины, ссылками на основные разделы и строкой поиска.

обновлено: 13.02.2020 1566399901

Александр Коваленко, CEO/founder агентства Advermedia.ua, опыт в SEO более 10 лет.
Канал автора в телеграм: @seomnenie

Информация о статье

Ошибка 404 - что означает, как создать и настроить

Заголовок

Ошибка 404 — что означает, как создать и настроить

Описание

Все о 404 ошибке: 1. Что означает 404 2. Как создать страницу 404 3. Как найти ошибки 404 на сайте 4. Как исправить

Автор

Организация

advermedia.ua

Логотип

advermedia.ua

Loading…

CEO/founder агентства Advermedia.ua, опыт в SEO более 10 лет.
Канал автора в телеграм: @seomnenie

Новые материалы

Подписаться на телеграм канал СEO Advermedia Мнение SEO

Публикуем интересные материалы из блога и разбираем вопросы по SEO от подписчиков!


https://t.me/seomnenie
Подписаться

mjt at jpeto dot net

13 years ago


I strongly recommend, that you use

header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");

instead of

header("HTTP/1.1 404 Not Found");

I had big troubles with an Apache/2.0.59 (Unix) answering in HTTP/1.0 while I (accidentially) added a "HTTP/1.1 200 Ok" - Header.

Most of the pages were displayed correct, but on some of them apache added weird content to it:

A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser)

"0" at the bottom of the page (after the complete output of my php script)

It took me quite a while to find out about the wrong protocol in the HTTP-header.

Marcel G

12 years ago


Several times this one is asked on the net but an answer could not be found in the docs on php.net ...

If you want to redirect an user and tell him he will be redirected, e. g. "You will be redirected in about 5 secs. If not, click here." you cannot use header( 'Location: ...' ) as you can't sent any output before the headers are sent.

So, either you have to use the HTML meta refresh thingy or you use the following:

<?php

  header

( "refresh:5;url=wherever.php" );

  echo

'You'll be redirected in about 5 secs. If not, click <a href="wherever.php">here</a>.';?>

Hth someone

Dylan at WeDefy dot com

15 years ago


A quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header().

<?php
// 301 Moved Permanently
header("Location: /foo.php",TRUE,301);// 302 Found
header("Location: /foo.php",TRUE,302);
header("Location: /foo.php");// 303 See Other
header("Location: /foo.php",TRUE,303);// 307 Temporary Redirect
header("Location: /foo.php",TRUE,307);
?>

The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it's a good idea to set the status code at the same time.  Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely.  Search engines typically transfer "page rank" to the new location for 301 redirects, but not for 302, 303 or 307. If the status code is not specified, header('Location:') defaults to 302.

mandor at mandor dot net

16 years ago


When using PHP to output an image, it won't be cached by the client so if you don't want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol.

Here's how:

<?php// Test image.
   
$fn = '/test/foo.png';// Getting headers sent by the client.
   
$headers = apache_request_headers(); // Checking if the client is validating his cache and if it is current.
   
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($fn))) {
       
// Client's cache IS current, so we just respond '304 Not Modified'.
       
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
    } else {
       
// Image not cached or cache outdated, we respond '200 OK' and output the image.
       
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
       
header('Content-Length: '.filesize($fn));
       
header('Content-Type: image/png');
        print
file_get_contents($fn);
    }
?>

That way foo.png will be properly cached by the client and you'll save bandwith. :)

php at ober-mail dot de

3 years ago


Since PHP 5.4, the function `http_​response_​code()` can be used to set the response code instead of using the `header()` function, which requires to also set the correct protocol version (which can lead to problems, as seen in other comments).

bebertjean at yahoo dot fr

14 years ago


If using the 'header' function for the downloading of files, especially if you're passing the filename as a variable, remember to surround the filename with double quotes, otherwise you'll have problems in Firefox as soon as there's a space in the filename.

So instead of typing:

<?php
  header
("Content-Disposition: attachment; filename=" . basename($filename));
?>

you should type:

<?php
  header
("Content-Disposition: attachment; filename="" . basename($filename) . """);
?>

If you don't do this then when the user clicks on the link for a file named "Example file with spaces.txt", then Firefox's Save As dialog box will give it the name "Example", and it will have no extension.

See the page called "Filenames_with_spaces_are_truncated_upon_download" at
http://kb.mozillazine.org/ for more information. (Sorry, the site won't let me post such a long link...)

tim at sharpwebdevelopment dot com

4 years ago


The header call can be misleading to novice php users.
when "header call" is stated, it refers the the top leftmost position of the file and not the "header()" function itself.
"<?php" opening tag must be placed before anything else, even whitespace.

nospam at nospam dot com

6 years ago


<?php// Response codes behaviors when using
header('Location: /target.php', true, $code) to forward user to another page:$code = 301;
// Use when the old page has been "permanently moved and any future requests should be sent to the target page instead. PageRank may be transferred."$code = 302; (default)
// "Temporary redirect so page is only cached if indicated by a Cache-Control or Expires header field."$code = 303;
// "This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource and is not cached."$code = 307;
// Beware that when used after a form is submitted using POST, it would carry over the posted values to the next page, such if target.php contains a form processing script, it will process the submitted info again!

// In other words, use 301 if permanent, 302 if temporary, and 303 if a results page from a submitted form.
// Maybe use 307 if a form processing script has moved.

?>

yjf_victor

7 years ago


According to the RFC 6226 (https://tools.ietf.org/html/rfc6266), the only way to send Content-Disposition Header with encoding is:

Content-Disposition: attachment;
                          filename*= UTF-8''%e2%82%ac%20rates

for backward compatibility, what should be sent is:

Content-Disposition: attachment;
                          filename="EURO rates";
                          filename*=utf-8''%e2%82%ac%20rates

As a result, we should use

<?php
$filename
= '中文文件名.exe';   // a filename in Chinese characters$contentDispositionField = 'Content-Disposition: attachment; '
   
. sprintf('filename="%s"; ', rawurlencode($filename))
    .
sprintf("filename*=utf-8''%s", rawurlencode($filename));header('Content-Type: application/octet-stream');header($contentDispositionField);readfile('file_to_download.exe');
?>

I have tested the code in IE6-10, firefox and Chrome.

sk89q

14 years ago


You can use HTTP's etags and last modified dates to ensure that you're not sending the browser data it already has cached.

<?php

$last_modified_time

= filemtime($file);$etag = md5_file($file);
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");header("Etag: $etag");

if (@

strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {header("HTTP/1.1 304 Not Modified");

    exit;

}

?>

David

5 years ago


It seems the note saying the URI must be absolute is obsolete. Found on https://en.wikipedia.org/wiki/HTTP_location

«An obsolete version of the HTTP 1.1 specifications (IETF RFC 2616) required a complete absolute URI for redirection.[2] The IETF HTTP working group found that the most popular web browsers tolerate the passing of a relative URL[3] and, consequently, the updated HTTP 1.1 specifications (IETF RFC 7231) relaxed the original constraint, allowing the use of relative URLs in Location headers.»

ben at indietorrent dot org

10 years ago


Be aware that sending binary files to the user-agent (browser) over an encrypted connection (SSL/TLS) will fail in IE (Internet Explorer) versions 5, 6, 7, and 8 if any of the following headers is included:

Cache-control:no-store
Cache-control:no-cache

See: http://support.microsoft.com/kb/323308

Workaround: do not send those headers.

Also, be aware that IE versions 5, 6, 7, and 8 double-compress already-compressed files and do not reverse the process correctly, so ZIP files and similar are corrupted on download.

Workaround: disable compression (beyond text/html) for these particular versions of IE, e.g., using Apache's "BrowserMatch" directive. The following example disables compression in all versions of IE:

BrowserMatch ".*MSIE.*" gzip-only-text/html

dev at omikrosys dot com

13 years ago


Just to inform you all, do not get confused between Content-Transfer-Encoding and Content-Encoding

Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).
Eg Use:- header('Content-Transfer-Encoding: binary');

Content-Encoding is used to apply things like gzip compression to the content/data.
Eg Use:- header('Content-Encoding: gzip');

chris at ocproducts dot com

6 years ago


Note that 'session_start' may overwrite your custom cache headers.
To remedy this you need to call:

session_cache_limiter('');

...after you set your custom cache headers. It will tell the PHP session code to not do any cache header changes of its own.

shutout2730 at yahoo dot com

14 years ago


It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.

This redirects to 2.html since the second header replaces the first.

<?php
header
("location: 1.html");
header("location: 2.html"); //replaces 1.html
?>

This redirects to 1.html since the header is sent as soon as the echo happens. You also won't see any "headers already sent" errors because the browser follows the redirect before it can display the error.

<?php
header
("location: 1.html");
echo
"send data";
header("location: 2.html"); //1.html already sent
?>

Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren't sent until the output buffer is flushed.

<?php
ob_start
();
header("location: 1.html");
echo
"send data";
header("location: 2.html"); //replaces 1.html
ob_end_flush(); //now the headers are sent
?>

jp at webgraphe dot com

19 years ago


A call to session_write_close() before the statement

<?php

    header

("Location: URL");

    exit();

?>

is recommended if you want to be sure the session is updated before proceeding to the redirection.

We encountered a situation where the script accessed by the redirection wasn't loading the session correctly because the precedent script hadn't the time to update it (we used a database handler).

JP.

David Spector

1 year ago


Please note that there is no error checking for the header command, either in PHP, browsers, or Web Developer Tools.

If you use something like "header('text/javascript');" to set the MIME type for PHP response text (such as for echoed or Included data), you will get an undiagnosed failure.

The proper MIME-setting function is "header('Content-type: text/javascript');".

mzheng[no-spam-thx] at ariba dot com

14 years ago


For large files (100+ MBs), I found that it is essential to flush the file content ASAP, otherwise the download dialog doesn't show until a long time or never.

<?php
header
("Content-Disposition: attachment; filename=" . urlencode($file));   
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");            
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.$fp = fopen($file, "r");
while (!
feof($fp))
{
    echo
fread($fp, 65536);
   
flush(); // this is essential for large downloads

fclose($fp);
?>

razvan_bc at yahoo dot com

5 years ago


<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>

this example is pretty good BUT in time you use "exit" the parser will still work to decide what's happening next the "exit" 's action should do ('cause if you check the manual exit works in others situations too).
SO MY POINT IS : you should use :
<?php

header

('Location: http://www.example.com/');
die();
?>
'CAUSE all die function does is to stop the script ,there is no other place for interpretation and the scope you choose to break the action of your script is quickly DONE!!!

there are many situations  with others examples and the right choose for small parts of your scrips that make differences when you write your php framework at well!

Thanks Rasmus Lerdorf and his team to wrap off parts of unusual php functionality ,php 7 roolez!!!!!

Angelica Perduta

2 years ago


I made a script that generates an optimized image for use on web pages using a 404 script to resize and reduce original images, but on some servers it was generating the image but then not using it due to some kind of cache somewhere of the 404 status. I managed to get it to work with the following and although I don't quite understand it, I hope my posting here does help others with similar issues:

    header_remove();
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    // ... and then try redirecting
    // 201 = The request has been fulfilled, resulting in the creation of a new resource however it's still not loading
    // 302 "moved temporarily" does seems to load it!
    header("location:$dst", FALSE, 302); // redirect to the file now we have it

scott at lucentminds dot com

13 years ago


If you want to remove a header and keep it from being sent as part of the header response, just provide nothing as the header value after the header name. For example...

PHP, by default, always returns the following header:

"Content-Type: text/html"

Which your entire header response will look like

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Content-Type: text/html; charset=UTF-8
Connection: close

If you call the header name with no value like so...

<?php

    header

( 'Content-Type:' );?>

Your headers now look like this:

HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Connection: close

Vinay Kotekar

8 years ago


Saving php file in ANSI  no isuess but when saving the file in UTF-8 format for various reasons remember to save the file without any BOM ( byte-order mark) support.
Otherwise you will face problem of headers not being properly sent
eg.
<?php header("Set-Cookie: name=user");?>

Would give something like this :-

Warning: Cannot modify header information - headers already sent by (output started at C:wwwinfo.php:1) in C:wwwinfo.php on line 1

Cody G.

12 years ago


After lots of research and testing, I'd like to share my findings about my problems with Internet Explorer and file downloads.

  Take a look at this code, which replicates the normal download of a Javascript:

<?php
if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
 
header("Content-type: text/javascript");
 
header("Content-Disposition: inline; filename="download.js"");
 
header("Content-Length: ".filesize("my-file.js"));
} else {
 
header("Content-type: application/force-download");
 
header("Content-Disposition: attachment; filename="download.js"");
 
header("Content-Length: ".filesize("my-file.js"));
}
header("Expires: Fri, 01 Jan 2010 05:00:00 GMT");
if(
strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
 
header("Cache-Control: no-cache");
 
header("Pragma: no-cache");
}
include(
"my-file.js");
?>

Now let me explain:

  I start out by checking for IE, then if not IE, I set Content-type (case-sensitive) to JS and set Content-Disposition (every header is case-sensitive from now on) to inline, because most browsers outside of IE like to display JS inline. (User may change settings). The Content-Length header is required by some browsers to activate download box. Then, if it is IE, the "application/force-download" Content-type is sometimes required to show the download box. Use this if you don't want your PDF to display in the browser (in IE). I use it here to make sure the box opens. Anyway, I set the Content-Disposition to attachment because I already know that the box will appear. Then I have the Content-Length again.

  Now, here's my big point. I have the Cache-Control and Pragma headers sent only if not IE. THESE HEADERS WILL PREVENT DOWNLOAD ON IE!!! Only use the Expires header, after all, it will require the file to be downloaded again the next time. This is not a bug! IE stores downloads in the Temporary Internet Files folder until the download is complete. I know this because once I downloaded a huge file to My Documents, but the Download Dialog box put it in the Temp folder and moved it at the end. Just think about it. If IE requires the file to be downloaded to the Temp folder, setting the Cache-Control and Pragma headers will cause an error!

I hope this saves someone some time!
~Cody G.

Anonymous

13 years ago


I just want to add, becuase I see here lots of wrong formated headers.

1. All used headers have first letters uppercase, so you MUST follow this. For example:

Location, not location

Content-Type, not content-type, nor CONTENT-TYPE

2. Then there MUST be colon and space, like

good: header("Content-Type: text/plain");

wrong: header("Content-Type:text/plain");

3. Location header MUST be absolute uri with scheme, domain, port, path, etc.

good: header("Location: http://www.example.com/something.php?a=1");

4. Relative URIs are NOT allowed

wrong:  Location: /something.php?a=1

wrong:  Location: ?a=1

It will make proxy server and http clients happier.

Refugnic

12 years ago


My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file.

After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to 'Always perform this operation with this file type'.

As I found out, the problem was in the header directive 'Content-Disposition', namely the 'attachment' directive.

If you want your browser to simulate a plain link to a file, either change 'attachment' to 'inline' or omit it alltogether and you'll be fine.

This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem.

bMindful at fleetingiamge dot org

19 years ago


If you haven't used, HTTP Response 204 can be very convenient. 204 tells the server to immediately termiante this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.

     header("status: 204");  (or the other call)

     header("HTTP/1.0 204 No Response");

nobileelpirata at hotmail dot com

15 years ago


This is the Headers to force a browser to use fresh content (no caching) in HTTP/1.0 and HTTP/1.1:

<?PHP

header

( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' );header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );header( 'Cache-Control: no-store, no-cache, must-revalidate' );header( 'Cache-Control: post-check=0, pre-check=0', false );header( 'Pragma: no-cache' );
?>

jamie

14 years ago


The encoding of a file is discovered by the Content-Type, either in the HTML meta tag or as part of the HTTP header. Thus, the server and browser does not need - nor expect - a Unicode file to begin with a BOM mark. BOMs can confuse *nix systems too. More info at http://unicode.org/faq/utf_bom.html#bom1

On another note: Safari can display CMYK images (at least the OS X version, because it uses the services of QuickTime)

er dot ellison dot nyc at gmail dot com

7 years ago


DO NOT PUT space between location and the colon that comes after that ,
// DO NOT USE THIS :
header("Location : #whatever"); // -> will not work !

// INSTEAD USE THIS ->
header("Location: #wahtever"); // -> will work forever !

hamza dot eljaouhari dot etudes at gmail dot com

4 years ago


// Beware that adding a space between the keyword "Location" and the colon causes an Internal Sever Error

//This line causes the error
        7
header('Location : index.php&controller=produit&action=index');

// While It must be written without the space
header('Location: index.php&controller=produit&action=index');

ASchmidt at Anamera dot net

4 years ago


Setting the "Location: " header has another undocumented side-effect!

It will also disregard any expressly set "Content-Type: " and forces:

"Content-Type: text/html; charset=UTF-8"

The HTTP RFCs don't call for such a drastic action. They simply state that a redirect content SHOULD include a link to the destination page (in which case ANY HTML compatible content type would do). But PHP even overrides a perfectly standards-compliant
"Content-Type: application/xhtml+xml"!

cedric at gn dot apc dot org

12 years ago


Setting a Location header "returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set".  If you are sending a response to a POST request, you might want to look at RFC 2616 sections 10.3.3 and 10.3.4.   It is suggested that if you want the browser to immediately GET the resource in the Location header in this circumstance, you should use a 303 status code not the 302 (with the same link as hypertext in the body for very old browsers).  This may have (rare) consequences as mentioned in bug 42969.

20.01.2021

Марат

1728

0

php | header | 404 |

header 404. Как отправить на сервер заголовок header 404.
Ошибка отправки заголовка header 404. Все темы с примерами!

Всё о header(«HTTP/1.0 404 «)

  1. Код php заголовка 404
  2. Ошибка отправки header 404
  3. Для чего отправлять header 404, видео
  4. Пример отправки header 404
  5. Проверить попал ли в header 404
  6. Скачать можно здесь
  1. Код php заголовка 404

    Для того, чтобы отправить заголовок на сервер header 404 надо написать вот такую строчку:

    header(«HTTP/1.0 404 «);

    Естественно, что отправка 404 на сервер с помощью header должна осуществляться в самом верху страницы.

    ВНИМАНИЕ! ЭТО ВАЖНО!
    В самом верху страницы — это значит, что никакого, символа, ни точки, ни пробела ни переноса — вообще ничего, если у вас есть впереди php код, то код должен быть таким:

    <?

    здесь может быть сколько угодно кода php //

    НО! — никакого echo, print_r, var_dump и других выводящих функций!

    header(«HTTP/1.0 404 «);
    exit ;//

    используется в том случае, если требуется остановить выполнение ниже идущего кода.

    ?>

  2. Ошибка отправки header 404

    Если вы отправите заголовок header 404, как показано ниже, то вы получите ошибку отправки header 404:

    <?

    здесь код

    ?>

    <br> Привет мир

    <?

    header(«HTTP/1.0 404 «);

    ?>

    Пример ошибки отправки header 404:

    Если перед отправкой заголовка header 404 будет выводящий код, то получите ошибку.
    Давайте сделаем ошибку отправки header 404 специально!!
    Поместим какой-то текст произвольного содержания, перед отправкой header 404 :

    echo ‘Здесь текст, который выводится ранее, чем header 404’;

    header(«HTTP/1.0 404 «);

    Посмотрим это на скрине:
    Пример ошибки отправки header 404:

    Вывод ошибки отправки header 404

    Здесь текст, который выводится ранее, чем header 404

    Warning: Cannot modify header information — headers already sent by (output started at

    путь/page/php/header/001_header_404.html:3) in

    путь/page/php/header/001_header_404.html on line 4

    Вывод ошибки отправки header 404 на странице

    Вывод ошибки отправки header 404 на странице

  3. Для чего отправлять header 404

    Чтобы не гадать — по какой из причин вам может понадобится использовать отправку заголовка header 404 -приведу собственную причину использования header 404.
    На нашем сайте используется единая точка входа, — по всем запросам в адресной строке… будут перенаправляться на ту страницу, на которую настроена переадресация!

    И даже те, страницы, которые не существуют… все равно будут перенаправляться… на главную.

    Вот как раз для такого случая…

    Естественно, что ничего не понятно!

    Я делал специальное видео, где использовал приведенный код!

    Видео — использование header 404

    Друзья!

    Мне очень нужны подписчики!
    Пожалуйста подпишись на Дзене!
    Заранее спасибо!

  4. Пример отправки header 404

    Для того, чтобы разобраться в том, как работает отправка заголовка header 404 нам потребуется какая-то страница, которая не существует!

    Вообще любая!

    Например такая :

    У вас должна открыться такая страница 404 (несколько тем посвятили теме 404)
    Пример отправки header 404
    Но где здесь отправленный header 404 через php!? Этот скрин я вам привел специально — если вы захотите, то сделал отдельный архив -> сложил 404 через php + задний фон второй вариант 404 через php

    И теперь, чтобы увидеть, где заголовок надо -> нажимаем ctrl + U

    Нажмите, чтобы открыть в новом окне.

    Пример отправки header 404

  5. Проверить попал ли в header 404

    Как проверить правильно ли был отправлен заголовок с помощью header 404!?

    Если у вас возникли проблемы с пониманием того, что происходит заголовками, то существует огромное количество сайтов, которые могут показать всё, что вы отправляете!

    Выбрал первый попавший… https://bertal.ru/ — заходим на сайт в вставляем в адресную строку свой адрес страницы.

    Нажмите, чтобы открыть в новом окне.

    Проверить попал ли в header 404

P.S.

Вообще… после случая с санкциями… пошел посмотреть, а что вообще творится со страницами на моем другом сайте и обнаружил, что робот проиндексировал папки(директории) – как отдельные страницы – и описанная тема… как раз востребована была там.

Можете не благодарить, лучше помогите!

Название скрипта :php header 404

COMMENTS+

 
BBcode


Как сделать 404 страницу

Постараюсь не сильно вдаваться в подробности, что такое 404-ая страница, достаточно открыть гугл и по запросу «Как сделать 404 страницу» — Вы обнаружите огромное количество сайтов с подробным описанием, что это такое. Я просто хочу поделиться с читателем своим способом создания 404-ой страницы. И вот, что у нас должно получиться в итоге.

Как сделать 404 страницу

Почему обязательно надо делать свою 404-ую страницу?

Главная и единственная причина – это не потерять посетителя. У каждого пользователя наверняка возникала такая ситуация, когда нажимая на ссылки на каком-нибудь сайте, браузер вместо запрашиваемой страницы показывал свою дефолтную страницу ошибки. Ошибка возникает в результате неправильно введенного запроса или запрашиваемая страница, была удалена самим веб-мастером. В таком случае все посетители ведут себя одинаково – закрывают страницу и уходят с вашего сайта.

Хватит воду лить! Давай конкретику!

Создаем два файла – 404.html и .htaccess (этот файл без имени, но с расширением htaccess), который автоматически перенаправляет посетителя на 404.html, в случае возникновения ошибки. Чтобы перенаправление работало, в этот файл надо прописать одну единственную строку:


ErrorDocument 404 http://www.site.ru/404.html

Когда оба файла будут готовы, залить их на сервер в корень домена.

Мы уже создали пустой файл 404.html и теперь будем наполнять HTML кодом саму 404 страницу, активно применяя HTML5 и CSS3. Я придумал свой способ, как сделать простую и красивую 404 страницу.

Первым делом нужно подобрать большую и качественную картинку или фотографию размером не менее 1200×750 пикселей. Существует много сайтов со свободной лицензией, откуда можно скачать очень качественные фотографии. Я бесплатно скачал с популярного сайта pixabay.com это забавное изображение.

Как сделать 404 страницу

Я хочу расположить картинку как фон на все окно браузера и в центре браузера написать – 404 страница не найдена и поставить ссылку на главную. Разберем подробнее самые важные моменты.

Эффект полупрозрачности RGBA

Выбранное изображение слишком яркое, надо его слегка затемнить, тогда текст будет более читаемый. Эффект полупрозрачного затемнения, можно получить используя RGBA, прописав в стилях блока следующую строчку кода:


background: rgba (0, 0, 0, 0.7);

Первые три буквы обозначают – красный, зеленый, синий и они равны нулю (то есть получаем черный цвет). А последняя буква «а» – представляет собой альфа-канал, отвечающий за полупрозрачность элемента. В нашем случае цифра 0.7 – говорит о 70% затемнения. Шкала от полной прозрачности до полной непрозрачности находиться между нулем и единицей (0…1).

Позиционирование элементов

Для правильной верстки моего примера 404 страницы, без понимания как работает свойство position, будет трудно. Посмотрев на конечный результат 404 страницы, нам надо понять структуру HTML документа. Здесь мы видим три слоя, наложенных друг на друга. Нижний слой <body> – сама картинка, средний в теге <div> – полупрозрачный блок затемнения и верхний <div> – текст. Наша задача задать нужное позиционирование содержимого этих слоев.

У среднего слоя будет абсолютное позиционирование, поскольку положение элемента (блок затемнения) задается относительно краев браузера с нулевыми отступами.


position: absolute;

Верхний текстовый слой позиционируем относительно элемента среднего слоя.


position: relative;

Код страницы 404

Имея этот готовый код и меняя только само изображение, можно наделать себе массу разных «ошибочных» страниц.


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Код страницы 404</title>
<style>
html { height: 100%; }
body {
  background: url(your_image.jpg) no-repeat;
  background-size: cover; /* Масштабирует картинку сохраняя пропорции */
  }
.over {
  background: rgba(0, 0, 0, 0.7); /* Цвет фона и значение прозрачности */
  position: absolute; /* Абсолютное позиционирование */
  left: 0; right: 0; top: 0; bottom: 0; /* Отступы от краев браузера */
  }
.404 {
  margin-top: 100px;
  text-align: center; /* Выравнивание текста по центру */
  font-size: 10em;
  color: #fcf9f9;
  position: relative; /* Относительное позиционирование */
  z-index: 2; /* Порядок наложения элемента по высоте */
  }
.notfound {
  text-align: center;
  color: #fff;
  font-size: 2em;
  position: relative; /* Относительное позиционирование */
  z-index: 2; /* Порядок наложения элемента по слоям в глубину */
  }
.notfound a {
  color: #fff;
  font-size: 0.8em;
  }
.notfound a:hover {
  color: yellow;
  text-decoration: none;
  }
</style>
</head>
<body>
<div class="over"></div>
<div class="404">404</div>
<div class="notfound">страница не найдена<br>
<a href="#"> перейти на главную страницу..</a>
</div>
</body>
</html>

Если Вы планируете заниматься созданием сайтов на заказ, то разобраться во всех тонкостях верстки, используя HTML5 и CSS3, Вам поможет мой видеокурс.

  • Создано 05.10.2017 01:11:33


  • Михаил Русаков

Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

  1. Кнопка:

    Она выглядит вот так: Как создать свой сайт

  2. Текстовая ссылка:

    Она выглядит вот так: Как создать свой сайт

  3. BB-код ссылки для форумов (например, можете поставить её в подписи):

Ошибка 404Я решил перенести большую часть файлов со старого сайта на новый. И у меня возник вопрос — «А не обвинит ли меня Yandex в использовании неуникальных статей?», т.к. у меня одни и те же материалы будут на разных страницах.

Я написал письмо в службу поддержки yandex, и мне пришло письмо, в котором сообщалось, что переживать не надо. Единственно, настоятельно желательно, чтобы я каким-то способом закрыл старые странички от индексирования (через robots.txt, вызов ошибки 404 или перенаправление) и удалил странички из базы по адресу http://webmaster.yandex.ru/delurl.xml. Удалять по указанному адресу желательно, чтобы быстрее прекратилась индексация страниц.

По некоторым причинам я предпочел способ вызова ошибки 404. Ошибка 404 вызывается в том случае, если ресурс на который идет ссылка не обнаружен. И тут я обнаружил, что у меня то и нет вызова этой ошибки, т.е. какие бы данные пользователь не ввел бы на старом сайте, что-то все равно выводится. Такая ситуация на мой взгляд не допустима, и я пошел с ней бороться.

Мой сайт написан был на php, поэтому я очень быстро нашел команду для вызова ошибки 404. Она имеет вид:

header("HTTP/1.0 404 Not Found");
exit;

Казалось бы все просто, но нет же. Никак эти две команды не хотели работать. Тогда я почитал дополнительно материал и выяснил, что  header() должна вызываться до отправки любого другого вывода. Т.е. она должна быть исключительно самой первой при выводе, поэтому ее нельзя использовать внутри require_once().

Но как оказалось существуют три замечательные функции, которые позволяют решить эту проблему:

  • ob_start() — задает начало области, которую надо поместить в буфер, я поместил ее самой первой при выводе.

  • ob_end_flush() — окончание задания буфер и сразу вывод. Т.е. первые две функции задают область, которую сначала нужно вывести в буфер, а потом сразу вывести.
  • ob_end_clean() — очищает буфер, и следующая команда как бы выводится самой первой.

С использованием этих команд организация вызова ошибки 404 выглядит следующим образом:

  1. Самая первая команда — ob_start()
  2. Далее идет основное содержание, которое пока копируется в буфер.
  3. Проверка на предмет вызова ошибки 404. Например, проверка наличия определенного значения. Если после проверки имеются причины вызвать ошибку, то задается код:
    ob_end_clean() ;
    header("HTTP/1.0 404 Not Found");
    exit;

    Тем самым будет выдано сообщение об ошибке и осуществлен выход.

  4. Выводим содержимое буфера командой ob_end_flush(). Идея в том, что если была вызвана ошибка, то сюда не попадем. Если ошибки не было, то выводим буфер.

Далее в файле .htaccess можно указать файл, который будет сопоставляться ошибке 404, но это уже совершенно другая история…

Добрый день всем, сегодня на очереди 404 страница. 404 страница – это страница, которая открывается тогда, когда пользователь переходит по не существующему адресу (URL). Я уверен, Вы ее часто встречали. Приведу Вам пример 404 страницы моего блога:


Если Вы “в живую” хотите увидеть как же выглядит эта “волшебная страница” на WPnew.ru, просто наберите в строке браузера несуществующий адрес в блоге. Например, я ввел случайный набор чисел и букв:

Вы также можете посмотреть у себя на блоге, как выглядит 404 страница. Если она Вас устраивает, оставьте ее таковой, если же нет, читайте дальше, мы вместе будет создавать/редактировать “страницу неправильного адреса”.

404 страница нужно обязательно! Она позволит удержать посетителя Вашего блога. Обычно те, кто видят стандартную 404 страницу ошибки, просто уходят с блога (а что еще делать, если перед их глазами какая-то непонятная надпись “Error 404. Page not found”).

Давайте приступим.

  1. В шаблоне демонстрируемого блога (напомню, он имеет адрес FanBar.ru) не оказалась той самой заветной страницы. Если у Вас также ее нет, просто создаем страницу под названием 404.php в теме блога, а у кого она есть, откройте данный файл:
  2. После открытия файла добавьте на первую строчку следующее (если у Вас эта строчка уже есть, то не нужно):
    <!--?php get_header(); ?-->

    А в конце (последняя строчка) добавьте следующий код:

    <!--?php get_footer(); ?-->
  3. Откройте файл page.php и исходя из него поставьте примерно в то же место код:
    <!--?php get_sidebar(); ?-->

    Так как у каждого пользователя свой шаблон WordPress, я не могу рассказать Вам как точно сделать дизайн 404 страницы для Вашего блога. Ориентируйтесь на файл page.php, используйте FireBug, ознакомьтесь с языком CSS, экспериментируйте.

Готовая 404 страница.

Приведу пример 404.php блога FanBar.ru. Я в нее добавил все необходимые комментарии, чтобы объяснить Вам какой код что делает, чтобы облегчить Вам процесс создания 404 страницы ошибки. Эту страницу Вы можете скачать тут (просто разархивируйте архив), а кому лень скачивать, смотрите код ниже:

<!--Вывод шапки-->
<!--?php get_header(); ?-->

<!--Это вывод сайдбара, у Вас наверняка по-другому, и он стоит в конце, наверное,смотрите page.php.
Должно быть наподобие <?php get_sidebar(); ?>, поставьте ее туда же, где она стоит в page.php-->
<!--?php include_once("side1.php"); ?-->
<!--?php include_once("side2.php"); ?-->
<!--Конец вывода сайдбара-->

<!--Индивидуальный стиль шаблона, у Вас, наверняка что-то другое. Используйте FireBug, чтобы узнать название своего стиля-->
<div class="wrap">
<!--Конец стиля-->

<!--Название страницы-->
<h1 class="posttitle">Ошибка 404. Такая страница не найдена.</h1>
<!--Конец названия-->

<!--Начиная отсюда можно скопировать, просто заменив fanbar.ru на адрес своего блога и изменив страницу Контакты-->
<h3>Могут быть несколько причин:</h3>
<ul>
 	<li>Страница перемещена или переименована</li>
 	<li>Страница больше не существует на этом сайте.</li>
 	<li>URL не соответствует действительности.</li>
</ul>
<h3>Предлагаю перейти:</h3>
<ul>
 	<li><a href="https://fanbar.ru">На главную страницу</a></li>
 	<li><a href="https://fanbar.ru/kontakty">Написать в контакты</a></li>
</ul>
<!--Заканчивать процесс копирования тут-->
<h3>Также, можете воспользоваться поиском:</h3>
<!--Вывод поиска. Найдите на своем блоге поиск (обычно в sidebar.php и скопируйте оттуда. У меня он выглядит так-->

<form method="get" id="searchform" action="http://fanbar.ru/">
<div style="margin-left:70px;">
        <input alt="search" type="text" value="<?php echo wp_specialchars($s, 1); ?>" name="s" id="s"></div>
</form><!--Конец вывода поиска-->

<!--Вывод категорий блога. Можете просто скопировать-->
<h3>Или перейти в любую категорию блога:</h3>
<ul>
<!--?php wp_list_cats('sort_column=name'); ?--></ul>
<!--Конец вывода категорий блога.-->

<!--Закрытие стиля wrap, который был в начале. Читайте урок про CSS, если не понятно. -->

</div>
<!--Вывод футера (подвала) темы-->
<!--?php get_footer(); ?-->

В принципе, все. Будут вопросы – пишите в комментариях. И не забывайте завтра — воскресенье, бесплатная видеоконференция со мной. Участвуйте все!

_____________________________

Следующий урок: Урок 56 Плагин Tweetmeme: выводим кнопку retweet на блоге.

<!—Вывод шапки—>
<?php get_header(); ?><!—Это вывод сайдбара, у Вас наверняка по-другому, и он стоит в конце, наверное,смотрите page.php.
Должно быть наподобие <?php get_sidebar(); ?>, поставьте ее туда же, где она стоит в page.php—>
<?php include_once(«side1.php»); ?>
<?php include_once(«side2.php»); ?>
<!—Конец вывода сайдбара—><!—Индивидуальный стиль шаблона, у Вас, наверняка что-то другое. Используйте FireBug, чтобы узнать название своего стиля—>
<div class=»wrap»>
<!—Конец стиля—><!—Название страницы—>
<h1 class=»posttitle»>Ошибка 404. Такая страница не найдена.</h1></br>
<!—Конец названия—>

<!—Начиная отсюда можно скопировать, просто заменив fanbar.ru на адрес своего блога и изменив страницу Контакты—>
<h3>Могут быть несколько причин:</h3>
<ul>
<li>Страница перемещена или переименована</li>
<li>Страница больше не существует на этом сайте.</li>
<li>URL не соответствует действительности.</li>
</ul>
<h3>Предлагаю перейти:</h3>
<ul>
<li><a href=»http://fanbar.ru»>На главную страницу</a></li>
<li><a href=»http://fanbar.ru/kontakty»>Написать в контакты</a></li>
</ul>
<!—Заканчивать процесс копирования тут—>

<h3>Также, можете воспользоваться поиском:</h3>

<!—Вывод поиска. Найдите на своем блоге поиск (обычно в sidebar.php и скопируйте оттуда. У меня он выглядит так—>
<form method=»get» id=»searchform» action=»http://fanbar.ru/»>
<div style=»margin-left:70px;»>
<input alt=»search» type=»text» value=»<?php echo wp_specialchars($s, 1); ?>» name=»s» id=»s» />
</div>
</form>
<!—Конец вывода поиска—>

<!—Вывод категорий блога. Можете просто скопировать—>
<h3>Или перейти в любую категорию блога:</h3>
<ul>
<?php wp_list_cats(‘sort_column=name’); ?>
</ul>
<!—Конец вывода категорий блога.—>

<!—Закрытие стиля wrap, который был в начале. Читайте урок про CSS, если не понятно. —>
</div>

<!—Вывод футера (подвала) темы—>
<?php get_footer(); ?>

Как вам урок?

Спасибо, очень приятно быть полезными!

Лучшая благодарность — это комментарий к уроку и «шеринг» в соц. сетях. Спасибо!

Помогите стать лучше, скажите что не так?

Непонятно
Урок устарел
Другое

Спасибо за помощь в развитии проекта!

Содержание

  • 1 Пошаговое решение по созданию страницы 404 с помощью .htaccess
  • 2 Создание страницы 404 с помощью публикации материала в Joomla

Сколько раз вы видели «404 Страница не существует (Not Found)“, и какая у Вас была реакция? Попав на такую страницу большинство пользователей закрывают ее, и вместе с ним Вас сайт. В общем речь пойдет, что такое ошибка 404, как страницу с ошибкой сделать более полезной для пользователя, благодаря чему мы его сможем удержать на сайте.

Код 404 – это код не существующего документа (страницы). Такая ошибка возможна в нескольких случаях:

  • не верный адрес страницы;
  • некорректная ссылка на сайт.

Избавиться от этой ошибки невозможно, не верно указанные ссылки в сети обязательно появляться, пользователь 1-2 буквы может перепутать, следовательно 404 страница на сайте может стать единственной которую увидит посетитель. Раз избавиться нельзя, значит надо выжать из этой ошибки максимум полезного, т.е. сделать из неё своего рода начало, которое будет предшествовать приятному продолжению. Как должна выглядеть и что должно быть на 404 странице:

  1. Страница 404 должна стать началом сайта, почти как главная.
  2. Используйте юмор.
  3. Обязательно поиск, например поиск по сайту от google adsense.
  4. Порекомендуйте пройти посетителю на главную страницу сайта.
  5. Ссылка на карту сайта.
  6. Контакты для связи, е-майл, icq и т.д., или дайте ссылку на форму обратной связи.

Пошаговое решение по созданию страницы 404 с помощью .htaccess

  1. Создаем страницу в HTML под названием 404.html с необходимыми текстом и ссылками.
  2. Сохраняем ее в корне сайта.
  3. В .htaccess прописываем ErrorDocument 404 /404.html.

Создание страницы 404 с помощью публикации материала в Joomla

  1. Создаем материал с текстом об ошибке.
  2. Создаем меню с ссылкой на этот материал, например, 404.html. Модуль меню не публикуем и не удаляем.
  3. Меню создается для красоты URL, чтобы не было всяких index.php?bla-bla-bla…
  4. Из папки templates/system копируем файл error.php в папку templates/Название_шаблона.
  5. В файле templates/Название_шаблона/templateDetails.xml вписываем перечисление файла error.php. в разделе <files><filename>error.php</filename></files>.
  6. Заменяем содержимое нашего файла error.php на следующий код:

<?php
// no direct access
defined( ‘_JEXEC’ ) or die( ‘Restricted access’ );

?>
<!DOCTYPE HTML PUBLIC «-//W3C//DTD XHTML 1.0 Transitional//EN» «http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd»>
<html xmlns=»http://www.w3.org/1999/xhtml» xml:lang=»<?php echo $this->language; ?>» lang=»<?php echo $this->language; ?>» dir=»<?php echo $this->direction; ?>»>
<head>
</head>
<body>
<?php
if (($this->error->code) == ‘404’) {
header(«HTTP/1.0 404 Not Found»); /*отправляет код ошибки для поисковой системы*/
header(‘Location: 404.html’); /*открывает страницу ошибок для пользователя*/
exit;
}
?>
</body>
</html>

header(‘Location: 404.html’); – это адрес страницы ошибки «404.html», можно написать свой, например, тот который запомнили из меню (можно SEF-адрес).

Если без SEF, то адрес будет такой

header(‘Location: index.php?option=com_content&view=article&id=29’);

Где 29 – это ID материала.

Если выбирать этот вариант, то меню не нужно создавать, однако, такой URL не очень красив.

20.01.2021

Марат

44

0

php | header | 404 |

header 404. Как отправить на сервер заголовок header 404.
Ошибка отправки заголовка header 404. Все темы с примерами!

Всё о header(«HTTP/1.0 404 «)

  1. Код php заголовка 404
  2. Ошибка отправки header 404
  3. Для чего отправлять header 404, видео
  4. Пример отправки header 404
  5. Проверить попал ли в header 404
  6. Скачать можно здесь
  1. Код php заголовка 404

    Для того, чтобы отправить заголовок на сервер header 404 надо написать вот такую строчку:

    header(«HTTP/1.0 404 «);

    Естественно, что отправка 404 на сервер с помощью header должна осуществляться в самом верху страницы.

    ВНИМАНИЕ! ЭТО ВАЖНО!
    В самом верху страницы — это значит, что никакого, символа, ни точки, ни пробела ни переноса — вообще ничего, если у вас есть впереди php код, то код должен быть таким:

    <?

    здесь может быть сколько угодно кода php //

    НО! — никакого echo, print_r, var_dump и других выводящих функций!

    header(«HTTP/1.0 404 «);
    exit ;//

    используется в том случае, если требуется остановить выполнение ниже идущего кода.

    ?>

  2. Ошибка отправки header 404

    Если вы отправите заголовок header 404, как показано ниже, то вы получите ошибку отправки header 404:

    <?

    здесь код

    ?>

    <br> Привет мир

    <?

    header(«HTTP/1.0 404 «);

    ?>

    Пример ошибки отправки header 404:

    Если перед отправкой заголовка header 404 будет выводящий код, то получите ошибку.
    Давайте сделаем ошибку отправки header 404 специально!!
    Поместим какой-то текст произвольного содержания, перед отправкой header 404 :

    echo ‘Здесь текст, который выводится ранее, чем header 404’;

    header(«HTTP/1.0 404 «);

    Посмотрим это на скрине:
    Пример ошибки отправки header 404:

    Вывод ошибки отправки header 404

    Здесь текст, который выводится ранее, чем header 404

    Warning: Cannot modify header information — headers already sent by (output started at

    путь/page/php/header/001_header_404.html:3) in

    путь/page/php/header/001_header_404.html on line 4

    Вывод ошибки отправки header 404 на странице

    Вывод ошибки отправки header 404 на странице

  3. Для чего отправлять header 404

    Чтобы не гадать — по какой из причин вам может понадобится использовать отправку заголовка header 404 -приведу собственную причину использования header 404.
    На нашем сайте используется единая точка входа, — по всем запросам в адресной строке… будут перенаправляться на ту страницу, на которую настроена переадресация!

    И даже те, страницы, которые не существуют… все равно будут перенаправляться… на главную.

    Вот как раз для такого случая…

    Естественно, что ничего не понятно!

    Я делал специальное видео, где использовал приведенный код!

    Видео — использование header 404

    Друзья!

    Мне очень нужны подписчики!
    Пожалуйста подпишись на Дзене!
    Заранее спасибо!

  4. Пример отправки header 404

    Для того, чтобы разобраться в том, как работает отправка заголовка header 404 нам потребуется какая-то страница, которая не существует!

    Вообще любая!

    Например такая :

    У вас должна открыться такая страница 404 (несколько тем посвятили теме 404)
    Пример отправки header 404
    Но где здесь отправленный header 404 через php!? Этот скрин я вам привел специально — если вы захотите, то сделал отдельный архив -> сложил 404 через php + задний фон второй вариант 404 через php

    И теперь, чтобы увидеть, где заголовок надо -> нажимаем ctrl + U

    Нажмите, чтобы открыть в новом окне.

    Пример отправки header 404

  5. Проверить попал ли в header 404

    Как проверить правильно ли был отправлен заголовок с помощью header 404!?

    Если у вас возникли проблемы с пониманием того, что происходит заголовками, то существует огромное количество сайтов, которые могут показать всё, что вы отправляете!

    Выбрал первый попавший… https://bertal.ru/ — заходим на сайт в вставляем в адресную строку свой адрес страницы.

    Нажмите, чтобы открыть в новом окне.

    Проверить попал ли в header 404

P.S.

Вообще… после случая с санкциями… пошел посмотреть, а что вообще творится со страницами на моем другом сайте и обнаружил, что робот проиндексировал папки(директории) – как отдельные страницы – и описанная тема… как раз востребована была там.

Не благодарите, но ссылкой можете поделиться!

Название скрипта :php header 404

COMMENTS+

 
BBcode


I need to force a 404 on some posts based on conditions. I managed to do it ( although I don’t know if I did it the right way) and I’m a getting my 404.php template to load as expected.

My code:

function rr_404_my_event() {
  global $post;
  if ( is_singular( 'event' ) && !rr_event_should_be_available( $post->ID ) ) {
    include( get_query_template( '404' ) );
    exit; # so that the normal page isn't loaded after the 404 page
  }
}

add_action( 'template_redirect', 'rr_404_my_event', 1 );

Code 2 from this related question — same problem:

function rr_404_my_event() {
  global $post;
  if ( is_singular( 'event' ) && !rr_event_should_be_available( $post->ID ) ) {
    global $wp_query;
    $wp_query->set_404();
  }
}

add_action( 'wp', 'rr_404_my_event' );

My Issue:

Although it looks good, I get a status 200 OK if I check the network tab. Since it’s a status 200, I am afraid that search engines might index those pages too.

Expected Behaviour:

I want a status 404 Not Found to be sent.

Community's user avatar

asked Mar 22, 2013 at 6:53

RRikesh's user avatar

2

You could try the WordPress function status_header() to add the HTTP/1.1 404 Not Found header;

So your Code 2 example would be:

function rr_404_my_event() {
  global $post;
  if ( is_singular( 'event' ) && !rr_event_should_be_available( $post->ID ) ) {
    global $wp_query;
    $wp_query->set_404();
    status_header(404);
  }
}
add_action( 'wp', 'rr_404_my_event' );

This function is for example used in this part:

function handle_404() {
    ...cut...
    // Guess it's time to 404.
    $wp_query->set_404();
    status_header( 404 );
    nocache_headers();
    ...cut...
}

from the wp class in /wp-includes/class-wp.php.

So try using this modified Code 2 example in addition to your template_include code.

answered Mar 24, 2013 at 18:17

birgire's user avatar

birgirebirgire

65.9k7 gold badges109 silver badges236 bronze badges

3

This code worked for me:

add_action( 'wp', 'force_404' );
function force_404() {
    global $wp_query; //$posts (if required)
    if(is_page()){ // your condition
        status_header( 404 );
        nocache_headers();
        include( get_query_template( '404' ) );
        die();
    }
}

answered Mar 24, 2013 at 18:42

golchha21's user avatar

golchha21golchha21

4894 silver badges9 bronze badges

2

I wouldn’t recommend forcing a 404.

If you’re worried about search engines why not just do a «no-index,no-follow» meta on those pages and block it with robots.txt?

This may be a better way to block the content from being viewed

add_filter( 'template_include', 'nifty_block_content', 99 );

function nifty_block_content( $template ) {
  if ( is_singular( 'event' ) && !rr_event_should_be_available( $post->ID ) ) {
        $template = locate_template( array( 'nifty-block-content.php' ) );
     }
    return $template;
}

You could probably also use this method to load 404.php but I feel that using a page template might be a better option.

source

answered Mar 22, 2013 at 8:47

Brooke.'s user avatar

Brooke.Brooke.

3,8731 gold badge25 silver badges34 bronze badges

1

My solution:

add_action( 'wp', 'my_404' );
function my_404() 
{
    if ( is_404() ) 
    {
        header("Status: 404 Not Found");
        $GLOBALS['wp_query']->set_404();
        status_header(404);
        nocache_headers();
        //var_dump(getallheaders()); var_dump(headers_list()); die();
    }
}

answered Jul 21, 2014 at 12:24

T.Todua's user avatar

T.ToduaT.Todua

5,6298 gold badges47 silver badges77 bronze badges

1

I wanted to share the way I used the marked solution

function fail_safe_for_authors() {
    if ((is_user_logged_in()) && (is_author()) && ($_COOKIE["user_role"] !== "administrator")) {
            global $wp_query;
            $wp_query->set_404();
            status_header(404);
        }
}
add_action("wp", "fail_safe_for_authors");

I did this to separate all user types from the administrator, in this project, Only the admin can see the author.php page.

I hope it could help somebody else.

answered Oct 4, 2019 at 18:20

Gendrith's user avatar

The most robust way I’ve found of achieving this is to do it in the template_include filter, like so:

function wpse91900_force_404(string $template): string {
    if ($some_condition) {
        global $wp_query;

        $wp_query->set_404();
        status_header(404);
        nocache_headers();

        $template = get_404_template();
    }

    return $template;
}
add_filter("template_include", "wpse91900_force_404");

answered Feb 1, 2022 at 15:33

JacobTheDev's user avatar

JacobTheDevJacobTheDev

1,1715 gold badges16 silver badges35 bronze badges

Status codes are sent in the headers of HTTP requests. Your current function is hooked into a hook that will be called too late.

You should try to hook your function rr_404_my_event() into action send_headers.

I’m not sure if at that point in time it’s even possible to check the Post ID, but give this a go:

add_action( 'send_headers', 'rr_404_my_event' );
function rr_404_my_event() {
    global $post;
    if ( is_singular( 'event' ) && !rr_event_should_be_available( $post->ID ) ) {
        include( get_query_template( '404' ) );
        header('HTTP/1.0 404 Not Found');
        exit; 
    }
}

RRikesh's user avatar

RRikesh

5,5854 gold badges28 silver badges45 bronze badges

answered Mar 22, 2013 at 10:42

Marc Dingena's user avatar

Marc DingenaMarc Dingena

1,0721 gold badge9 silver badges22 bronze badges

3

Languages:
English
Creating an Error 404 Page 日本語
(Add your language)

While you work hard to make sure that every link actually goes to a specific web page on your site, there is always a chance that a link clicked will slam dunk and become a famous 404 ERROR PAGE NOT FOUND.

All is not lost. If your visitors encounter an error, why not be a helpful WordPress site administrator and present them with a message more useful than «NOT FOUND».

This lesson will teach you how to edit your «error» and «page not found» messages so they are more helpful to your visitors. We’ll also show how to ensure your web server displays your helpful custom messages. Finally, we’ll go over how to create a custom error page consistent with your Theme’s style.

Contents

  • 1 An Ounce of Prevention
  • 2 Understanding Web Error Handling
  • 3 Editing an Error 404 Page
  • 4 Creating an Error 404 Page
  • 5 Tips for Error Pages
    • 5.1 Writing Friendly Messages
    • 5.2 Add Useful Links
  • 6 Testing 404 Error Messages
  • 7 Help Your Server Find the 404 Page
  • 8 Questions About Error Files

An Ounce of Prevention

Some errors are avoidable, you should regularly check and double check all your links. Also, if you are deleting a popular but out-of-date post, consider deleting the body of the post, and replacing it with a link referring visitors to the new page.

Understanding Web Error Handling

Visitors encounter errors at even the best websites. As site administrator, you may delete out-of-date posts, but another website may have a link to your inside page for that post.

When a user clicks on a link to a missing page, the web server will send the user an error message such as 404 Not Found. Unless your webmaster has already written custom error messages, the standard message will be in plain text and that leaves the users feeling a bit lost.

Most users are quite capable of hitting the back key, but then you’ve lost a visitor who may not care to waste their time hunting for the information. So as not to lose that visitor, at the very least, you’ll want your custom message to provide a link to your home page.

The friendly way to handle errors is to acknowledge the error and help them find their way. This involves creating a custom Error Page or editing the one that came with your WordPress Theme.

Editing an Error 404 Page

Every theme that is shipped with WordPress has a 404.php file, but not all Themes have their own custom 404 error template file. If they do, it will be named 404.php. WordPress will automatically use that page if a Page Not Found error occurs.

The normal 404.php page shipped with your Theme will work, but does it say what you want it to say, and does it offer the kind of help you want it to offer? If the answer is no, you will want to customize the message in the template file.

To edit your Theme’s 404 error template file, open it in your favorite text editor and edit the message text to say what you want it to say. Then save your changes and upload it to the theme directory of your WordPress install.

While you are examining and editing your 404 template file, take a look at the simple structure of the 404.php file that is shipped with Twenty Thirteen. It basically features tags that display the header, sidebar, and footer, and also an area for your message:

<?php
/**
 * The template for displaying 404 pages (Not Found)
 *
 * @package WordPress
 * @subpackage Twenty_Thirteen
 * @since Twenty Thirteen 1.0
 */

get_header(); ?>

	<div id="primary" class="content-area">
		<div id="content" class="site-content" role="main">

			<header class="page-header">
				<h1 class="page-title"><?php _e( 'Not Found', 'twentythirteen' ); ?></h1>
			</header>

			<div class="page-wrapper">
				<div class="page-content">
					<h2><?php _e( 'This is somewhat embarrassing, isn’t it?', 'twentythirteen' ); ?></h2>
					<p><?php _e( 'It looks like nothing was found at this location. Maybe try a search?', 'twentythirteen' ); ?></p>

					<?php get_search_form(); ?>
				</div><!-- .page-content -->
			</div><!-- .page-wrapper -->

		</div><!-- #content -->
	</div><!-- #primary -->

<?php get_footer(); ?>

So, to change the error message your visitor sees, revise the text within the h1 heading and within the page-content class; if necessary, add more paragraphs below that.

Creating an Error 404 Page

If your WordPress Theme does not include a template file named 404.php, you can create your own.

Because every theme is different, there is no guarantee that copying over the 404.php template file found in the Twenty Thirteen Theme will work, but it’s a good place to start. The error page you copy from the Twenty Thirteen Theme will adopt the style of the current theme because it actually calls the header and footer of the current theme. That’s less work for you, and you may only have to edit the message to suit your particular needs.

To use the 404.php template file from the WordPress Twenty Thirteen Theme:

  1. Copy the file /wp-content/themes/twentythirteen/404.php into the directory of your current theme.
  2. Then, as described in the previous section, edit the error message to present your desired error message.

If copying the default 404.php into your theme directory does not work well with your theme, you can also:

  • Change the Default Theme’s 404.php template file’s header, sidebar, footer, and other codes to match the rest of the Theme’s layout.

Or

  • Copy the index.php file of your current theme to a file called 404.php.
  • Open that file and delete all sections dealing with posts or comments, see The Loop.
  • Then, edit your 404 error message.

Tips for Error Pages

There are various improvements you can make to your 404 Error web pages so let’s look at some of your options.

Writing Friendly Messages

When an error message is displayed, you can say many things to help a visitor feel reassured they’ve only encountered a minor glitch, and you’re doing the best you can to help them find the information they want. You can say something clever like:

"Oops, I screwed up and you discovered my fatal flaw. 
Well, we're not all perfect, but we try.  Can you try this
again or maybe visit our <a 
title="Our Site" href="http://example.com/index.php">Home 
Page</a> to start fresh.  We'll do better next time."

You should also attempt to show the user what they want. Check out the AskApache Google 404 Plugin to add google search results to your 404.php

Or, say something shorter and sweeter. Almost anything you say is better than 404 Error Page Not Found. You can find more information about writing 404 Error pages on the Internet, like List Apart’s Perfect 404.

As an implementation of the Perfect 404 page, this solution will tell the user it’s not their fault and email the site admin.
Helpful 404 page

When a visitor gets a 404 error page, it can be intimidating, and unhelpful. Using WordPress, you can take the edge off a 404 and make it helpful to users, and yourself, too, by emailing whenever the user clicks a link to a non-existent page.

<p>You 
<?php
#some variables for the script to use
#if you have some reason to change these, do.  but wordpress can handle it
$adminemail = get_option('admin_email'); #the administrator email address, according to wordpress
$website = get_bloginfo('url'); #gets your blog's url from wordpress
$websitename = get_bloginfo('name'); #sets the blog's name, according to wordpress

  if (!isset($_SERVER['HTTP_REFERER'])) {
    #politely blames the user for all the problems they caused
        echo "tried going to "; #starts assembling an output paragraph
	$casemessage = "All is not lost!";
  } elseif (isset($_SERVER['HTTP_REFERER'])) {
    #this will help the user find what they want, and email me of a bad link
	echo "clicked a link to"; #now the message says You clicked a link to...
        #setup a message to be sent to me
	$failuremess = "A user tried to go to $website"
        .$_SERVER['REQUEST_URI']." and received a 404 (page not found) error. ";
	$failuremess .= "It wasn't their fault, so try fixing it.  
        They came from ".$_SERVER['HTTP_REFERER'];
	mail($adminemail, "Bad Link To ".$_SERVER['REQUEST_URI'],
        $failuremess, "From: $websitename <noreply@$website>"); #email you about problem
	$casemessage = "An administrator has been emailed 
        about this problem, too.";#set a friendly message
  }
  echo " ".$website.$_SERVER['REQUEST_URI']; ?> 
and it doesn't exist. <?php echo $casemessage; ?>  You can click back 
and try again or search for what you're looking for:
  <?php include(TEMPLATEPATH . "/searchform.php"); ?>
</p>

Add Useful Links

If you encounter a «page not found» situation on the WordPress site, it is filled with helpful links to direct you to the various categories and areas of information within the WordPress site. Check it out at http://wordpress.org/brokenlink.php.

To add similar useful links to your 404 page, create a list, or a paragraph, so the visitor can easily determine which section might be useful to visit. Information of that nature is much better than having the user just reach a dead-end. To help you understand how to link to documents within your site, especially to Pages and Categories, see Linking_Posts_Pages_and_Categories.

Testing 404 Error Messages

To test your custom 404 page and message, just type a URL address into your browser for your website that doesn’t exist. Make one up or use something like:

http://example.com/fred.php

This is sure to result in an error unless you actually have a php file called fred. If your error page doesn’t look «right», you can go back and edit it so it works correctly and matches your Theme’s look and feel.

Help Your Server Find the 404 Page

By default, if WordPress cannot find a particular page it will look for the 404.php web page. However, there may be cases where the web server encounters a problem before WordPress is aware of it. In that case, you can still guarantee that your web server sends the visitor to your 404.php template file by configuring your web server for custom 404 error handling.

To tell your web server to use your custom error files, you’ll need to edit the .htaccess file in the main directory (where main index.php file resides) of your WordPress installation. If you don’t have an .htaccess file, see Editing Rewrite Rules (.htaccess) on how to create an .htaccess file.

To ensure the server finds your 404 page, add the following line to your .htaccess file:

ErrorDocument 404 /index.php?error=404

The url /index.php is root-relative, which means that the forward slash begins with the root folder of your site. If WordPress is in a subfolder or subdirectory of your site’s root folder named ‘wordpress’, the line you add to your .htaccess file might be:

ErrorDocument 404 /wordpress/index.php?error=404

Questions About Error Files

Why not just hard code the path all the way to the 404.php file?
By allowing index.php to call the error file, you ensure that the 404.php file used will change automatically as you change your theme.
What happens if I switch to a theme that does not have a 404.php file?
Visitors clicking on a broken link will just see a copy of the home page of your WordPress site (index.php), but the URL they see will be the URL of the broken link. That can confuse them, especially since there is no acknowledgement of the error. But this is still better than a getting a «NOT FOUND» message without any links or information that could help them find what they seek.

Понравилась статья? Поделить с друзьями:
  • Ошибка 404 история появления
  • Ошибка 404 история возникновения
  • Ошибка 404 имгур
  • Ошибка 404 или not found
  • Ошибка 404 загрузка не удалась