From Wikipedia, the free encyclopedia
In computer network communications, the HTTP 404, 404 not found, 404, 404 error, page not found or file not found error message is a hypertext transfer protocol (HTTP) standard response code, to indicate that the browser was able to communicate with a given server, but the server could not find what was requested. The error may also be used when a server does not wish to disclose whether it has the requested information.[1]
The website hosting server will typically generate a «404 Not Found» web page when a user attempts to follow a broken or dead link; hence the 404 error is one of the most recognizable errors encountered on the World Wide Web.
English Wikipedia’s 404 Page
Overview
When communicating via HTTP, a server is required to respond to a request, such as a web browser request for a web page, with a numeric response code and an optional, mandatory, or disallowed (based upon the status code) message. In code 404, the first digit indicates a client error, such as a mistyped Uniform Resource Locator (URL). The following two digits indicate the specific error encountered. HTTP’s use of three-digit codes is similar to the use of such codes in earlier protocols such as FTP and NNTP. At the HTTP level, a 404 response code is followed by a human-readable «reason phrase». The HTTP specification suggests the phrase «Not Found»[1] and many web servers by default issue an HTML page that includes both the 404 code and the «Not Found» phrase.
A 404 error is often returned when pages have been moved or deleted. In the first case, it is better to employ URL mapping or URL redirection by returning a 301 Moved Permanently response, which can be configured in most server configuration files, or through URL rewriting; in the second case, a 410 Gone should be returned. Because these two options require special server configuration, most websites do not make use of them.
404 errors should not be confused with DNS errors, which appear when the given URL refers to a server name that does not exist. A 404 error indicates that the server itself was found, but that the server was not able to retrieve the requested page.
Soft 404 errors
Some websites report a «not found» error by returning a standard web page with a «200 OK» response code, falsely reporting that the page loaded properly; this is known as a soft 404. The term «soft 404» was introduced in 2004 by Ziv Bar-Yossef et al.[2]
Soft 404s are problematic for automated methods of discovering whether a link is broken. Some search engines, like Yahoo and Google, use automated processes to detect soft 404s.[3] Soft 404s can occur as a result of configuration errors when using certain HTTP server software, for example with the Apache software, when an Error Document 404 (specified in a .htaccess file) is specified as an absolute path (e.g. http://example.com/error.html) rather than a relative path (/error.html).[4] This can also be done on purpose to force some browsers (like Internet Explorer) to display a customized 404 error message rather than replacing what is served with a browser-specific «friendly» error message (in Internet Explorer, this behavior is triggered when a 404 is served and the received HTML is shorter than a certain length, and can be manually disabled by the user).
There are also «soft 3XX» errors where content is returned with a status 200 but comes from a redirected page, such as when missing pages are redirected to the domain root/home page.
Proxy servers
Some proxy servers generate a 404 error when a 500-range error code would be more correct. If the proxy server is unable to satisfy a request for a page because of a problem with the remote host (such as hostname resolution failures or refused TCP connections), this should be described as a 5xx Internal Server Error, but might deliver a 404 instead. This can confuse programs that expect and act on specific responses, as they can no longer easily distinguish between an absent web server and a missing web page on a web server that is present.
Intentional 404s
In July 2004, the UK telecom provider BT Group deployed the Cleanfeed content blocking system, which returns a 404 error to any request for content identified as potentially illegal by the Internet Watch Foundation.[5] Other ISPs return a HTTP 403 «forbidden» error in the same circumstances.[6] The practice of employing fake 404 errors as a means to conceal censorship has also been reported in Thailand[7] and Tunisia.[8] In Tunisia, where censorship was severe before the 2011 revolution, people became aware of the nature of the fake 404 errors and created an imaginary character named «Ammar 404» who represents «the invisible censor».[9]
Microsoft Internet Server 404 substatus error codes
The webserver software developed by Microsoft, Microsoft’s Internet Information Services (IIS), returns a set of substatus codes with its 404 responses. The substatus codes take the form of decimal numbers appended to the 404 status code. The substatus codes are not officially recognized by IANA and are not returned by non-Microsoft servers.
Substatus codes
Microsoft’s IIS 7.0, IIS 7.5, and IIS 8.0 servers define the following HTTP substatus codes to indicate a more specific cause of a 404 error:
- 404.0 – Not found.
- 404.1 – Site Not Found.
- 404.2 – ISAPI or CGI restriction.
- 404.3 – MIME type restriction.
- 404.4 – No handler configured.
- 404.5 – Denied by request filtering configuration.
- 404.6 – Verb denied.
- 404.7 – File extension denied.
- 404.8 – Hidden namespace.
- 404.9 – File attribute hidden.
- 404.10 – Request header too long.
- 404.11 – Request contains double escape sequence.
- 404.12 – Request contains high-bit characters.
- 404.13 – Content length too large.
- 404.14 – Request URL too long.
- 404.15 – Query string too long.
- 404.16 – DAV request sent to the static file handler.
- 404.17 – Dynamic content mapped to the static file handler via a wildcard MIME mapping.
- 404.18 – Query string sequence denied.
- 404.19 – Denied by filtering rule.
- 404.20 – Too Many URL Segments.
Custom error pages
The Wikimedia 404 message
Web servers can typically be configured to display a customised 404 error page, including a more natural description, the parent site’s branding, and sometimes a site map, a search form or 404-page widget. The protocol level phrase, which is hidden from the user, is rarely customized. Internet Explorer, however, will not display custom pages unless they are larger than 512 bytes, opting instead to display a «friendly» error page.[10] Google Chrome included similar functionality, where the 404 is replaced with alternative suggestions generated by Google algorithms, if the page is under 512 bytes in size.[11] Another problem is that if the page does not provide a favicon, and a separate custom 404-page exists, extra traffic and longer loading times will be generated on every page view.[12][13]
Many organizations use 404 error pages as an opportunity to inject humor into what may otherwise be a serious website. For example, Metro UK shows a polar bear on a skateboard, and the web development agency Left Logic has a simple drawing program.[14] During the 2015 UK general election campaign the main political parties all used their 404 pages to either take aim at political opponents or show relevant policies to potential supporters.[15] In Europe, the NotFound project, created by multiple European organizations including Missing Children Europe and Child Focus, encourages site operators to add a snippet of code to serve customized 404 error pages[16] which provide data about missing children.[17]
While many websites send additional information in a 404 error message—such as a link to the homepage of a website or a search box—some also endeavor to find the correct web page the user wanted. Extensions are available for some content management systems (CMSs) to do this.[18]
Tracking 404 errors
A number of tools exist that crawl through a website to find pages that return 404 status codes. These tools can be helpful in finding links that exist within a particular website. The limitation of these tools is that they only find links within one particular website, and ignore 404s resulting from links on other websites. As a result, these tools miss out on 83% of the 404s on websites.[19] One way around this is to find 404 errors by analyzing external links.[20]
One of the most effective ways to discover 404 errors is by using Google Search Console, Google Analytics or crawling software.
Another common method is tracking traffic to 404 pages using log file analysis.[21] This can be useful to understand more about what 404s users reached on the site. Another method of tracking traffic to 404 pages is using JavaScript-based traffic tracking tools.[22]
See also
- Blue screen of death
- Funky caching
- Link rot
- List of HTTP status codes
References
- ^ a b Fielding, R.; Reschke, J. (June 2014). Fielding, R; Reschke, J (eds.). «RFC 7231, HTTP/1.1 Semantics and Content, Section 6.5.4 404 Not Found». ietf.org. doi:10.17487/RFC7231. S2CID 14399078. Retrieved 13 December 2018.
- ^ Ziv Bar-Yossef; Andrei Z. Broder; Ravi Kumar; Andrew Tompkins (2004). Sic Transit Gloria Telae: Towards an Understanding of the Web’s Decay. Proceedings of the 13th International Conference on World Wide Web (WWW). pp. 328–337. doi:10.1145/988672.988716. ISBN 978-1581138443. S2CID 587547.
- ^ «Why is your crawler asking for strange URLs that have never existed on my site?». Yahoo Ysearch Help page. Archived from the original on 15 July 2014. Retrieved 4 September 2013.
- ^ «Farewell to soft 404s». Google Official Blog. Retrieved 20 September 2008.
- ^ «LINX Public Affairs » Cleanfeed: the facts». Publicaffairs.linx.net. 10 September 2004. Archived from the original on 13 May 2011. Retrieved 6 March 2011.
- ^ «DEMON – Error 403». Retrieved 14 June 2012.
- ^ Sambandaraksa, Don (18 February 2009). «The old fake ‘404 Not Found’ routine — Dead link». Bangkok Post. Retrieved 12 September 2010.
- ^ Noman, Helmi (12 September 2008). «Tunisian journalist sues government agency for blocking Facebook, claims damage for the use of 404 error message instead of 403». Open Net Initiative. Retrieved 21 November 2010.
- ^ «Anti-censorship movement in Tunisia: creativity, courage and hope!». Global Voices Advocacy. 27 May 2010. Retrieved 28 August 2010.
- ^ «Friendly HTTP Error Pages». msdn.com. 18 August 2010. Archived from the original on 2 December 2010. Retrieved 14 June 2012.
- ^ «Issue 1695: Chrome needs option to turn off «Friendly 404″ displays». bugs.chromium.org. Retrieved 25 December 2021.
- ^ Heng, Christopher (7 September 2008). «What is Favicon.ico and How to Create a Favicon Icon for Your Website». The Site Wizard. Retrieved 23 February 2011.
- ^ «The Dastardly «favicon.ico not found» Error». Internet Folks. 3 August 1999.
- ^ «From skateboarding bears to missing children: The power of the 404 Not Found error page». Metro. 6 June 2011. Retrieved 16 April 2013.
- ^ «The political Page 404 war». BBC Newsbeat. 27 April 2015. Retrieved 18 May 2018.
- ^ «Notfound.org». notfound. notfound. Archived from the original on 2 September 2014.
- ^ «Missing children messages go on 404 error pages». BBC News. 27 September 2012. Retrieved 20 September 2014.
- ^ Swenson, Sahala (19 August 2008). «Make your 404 pages more useful». Official Google Webmaster Central Blog. Google, Inc. Retrieved 28 August 2009.
- ^ «Sources Leading To 404s». SpringTrax. Retrieved 11 February 2013.
- ^ Cushing, Anne (2 April 2013). «A Data-Centric Approach To Identifying 404 Pages Worth Saving». Search Engine Land. Retrieved 7 June 2013.
- ^ «Tracking and Preventing 404 Errors». 404errorpages.com. Retrieved 7 June 2013.
- ^ «Understand 404 Errors». SpringTrax.com. Retrieved 7 June 2013.
External links
- A More Useful 404
- 404 Not Found of the Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content specification, at the Internet Engineering Task Force
- ErrorDocument Directive – instructions on custom error pages for the Apache 2.0 web server
- 404: Not Found – an award-winning song about the error code
From Wikipedia, the free encyclopedia
In computer network communications, the HTTP 404, 404 not found, 404, 404 error, page not found or file not found error message is a hypertext transfer protocol (HTTP) standard response code, to indicate that the browser was able to communicate with a given server, but the server could not find what was requested. The error may also be used when a server does not wish to disclose whether it has the requested information.[1]
The website hosting server will typically generate a «404 Not Found» web page when a user attempts to follow a broken or dead link; hence the 404 error is one of the most recognizable errors encountered on the World Wide Web.
English Wikipedia’s 404 Page
Overview
When communicating via HTTP, a server is required to respond to a request, such as a web browser request for a web page, with a numeric response code and an optional, mandatory, or disallowed (based upon the status code) message. In code 404, the first digit indicates a client error, such as a mistyped Uniform Resource Locator (URL). The following two digits indicate the specific error encountered. HTTP’s use of three-digit codes is similar to the use of such codes in earlier protocols such as FTP and NNTP. At the HTTP level, a 404 response code is followed by a human-readable «reason phrase». The HTTP specification suggests the phrase «Not Found»[1] and many web servers by default issue an HTML page that includes both the 404 code and the «Not Found» phrase.
A 404 error is often returned when pages have been moved or deleted. In the first case, it is better to employ URL mapping or URL redirection by returning a 301 Moved Permanently response, which can be configured in most server configuration files, or through URL rewriting; in the second case, a 410 Gone should be returned. Because these two options require special server configuration, most websites do not make use of them.
404 errors should not be confused with DNS errors, which appear when the given URL refers to a server name that does not exist. A 404 error indicates that the server itself was found, but that the server was not able to retrieve the requested page.
Soft 404 errors
Some websites report a «not found» error by returning a standard web page with a «200 OK» response code, falsely reporting that the page loaded properly; this is known as a soft 404. The term «soft 404» was introduced in 2004 by Ziv Bar-Yossef et al.[2]
Soft 404s are problematic for automated methods of discovering whether a link is broken. Some search engines, like Yahoo and Google, use automated processes to detect soft 404s.[3] Soft 404s can occur as a result of configuration errors when using certain HTTP server software, for example with the Apache software, when an Error Document 404 (specified in a .htaccess file) is specified as an absolute path (e.g. http://example.com/error.html) rather than a relative path (/error.html).[4] This can also be done on purpose to force some browsers (like Internet Explorer) to display a customized 404 error message rather than replacing what is served with a browser-specific «friendly» error message (in Internet Explorer, this behavior is triggered when a 404 is served and the received HTML is shorter than a certain length, and can be manually disabled by the user).
There are also «soft 3XX» errors where content is returned with a status 200 but comes from a redirected page, such as when missing pages are redirected to the domain root/home page.
Proxy servers
Some proxy servers generate a 404 error when a 500-range error code would be more correct. If the proxy server is unable to satisfy a request for a page because of a problem with the remote host (such as hostname resolution failures or refused TCP connections), this should be described as a 5xx Internal Server Error, but might deliver a 404 instead. This can confuse programs that expect and act on specific responses, as they can no longer easily distinguish between an absent web server and a missing web page on a web server that is present.
Intentional 404s
In July 2004, the UK telecom provider BT Group deployed the Cleanfeed content blocking system, which returns a 404 error to any request for content identified as potentially illegal by the Internet Watch Foundation.[5] Other ISPs return a HTTP 403 «forbidden» error in the same circumstances.[6] The practice of employing fake 404 errors as a means to conceal censorship has also been reported in Thailand[7] and Tunisia.[8] In Tunisia, where censorship was severe before the 2011 revolution, people became aware of the nature of the fake 404 errors and created an imaginary character named «Ammar 404» who represents «the invisible censor».[9]
Microsoft Internet Server 404 substatus error codes
The webserver software developed by Microsoft, Microsoft’s Internet Information Services (IIS), returns a set of substatus codes with its 404 responses. The substatus codes take the form of decimal numbers appended to the 404 status code. The substatus codes are not officially recognized by IANA and are not returned by non-Microsoft servers.
Substatus codes
Microsoft’s IIS 7.0, IIS 7.5, and IIS 8.0 servers define the following HTTP substatus codes to indicate a more specific cause of a 404 error:
- 404.0 – Not found.
- 404.1 – Site Not Found.
- 404.2 – ISAPI or CGI restriction.
- 404.3 – MIME type restriction.
- 404.4 – No handler configured.
- 404.5 – Denied by request filtering configuration.
- 404.6 – Verb denied.
- 404.7 – File extension denied.
- 404.8 – Hidden namespace.
- 404.9 – File attribute hidden.
- 404.10 – Request header too long.
- 404.11 – Request contains double escape sequence.
- 404.12 – Request contains high-bit characters.
- 404.13 – Content length too large.
- 404.14 – Request URL too long.
- 404.15 – Query string too long.
- 404.16 – DAV request sent to the static file handler.
- 404.17 – Dynamic content mapped to the static file handler via a wildcard MIME mapping.
- 404.18 – Query string sequence denied.
- 404.19 – Denied by filtering rule.
- 404.20 – Too Many URL Segments.
Custom error pages
The Wikimedia 404 message
Web servers can typically be configured to display a customised 404 error page, including a more natural description, the parent site’s branding, and sometimes a site map, a search form or 404-page widget. The protocol level phrase, which is hidden from the user, is rarely customized. Internet Explorer, however, will not display custom pages unless they are larger than 512 bytes, opting instead to display a «friendly» error page.[10] Google Chrome included similar functionality, where the 404 is replaced with alternative suggestions generated by Google algorithms, if the page is under 512 bytes in size.[11] Another problem is that if the page does not provide a favicon, and a separate custom 404-page exists, extra traffic and longer loading times will be generated on every page view.[12][13]
Many organizations use 404 error pages as an opportunity to inject humor into what may otherwise be a serious website. For example, Metro UK shows a polar bear on a skateboard, and the web development agency Left Logic has a simple drawing program.[14] During the 2015 UK general election campaign the main political parties all used their 404 pages to either take aim at political opponents or show relevant policies to potential supporters.[15] In Europe, the NotFound project, created by multiple European organizations including Missing Children Europe and Child Focus, encourages site operators to add a snippet of code to serve customized 404 error pages[16] which provide data about missing children.[17]
While many websites send additional information in a 404 error message—such as a link to the homepage of a website or a search box—some also endeavor to find the correct web page the user wanted. Extensions are available for some content management systems (CMSs) to do this.[18]
Tracking 404 errors
A number of tools exist that crawl through a website to find pages that return 404 status codes. These tools can be helpful in finding links that exist within a particular website. The limitation of these tools is that they only find links within one particular website, and ignore 404s resulting from links on other websites. As a result, these tools miss out on 83% of the 404s on websites.[19] One way around this is to find 404 errors by analyzing external links.[20]
One of the most effective ways to discover 404 errors is by using Google Search Console, Google Analytics or crawling software.
Another common method is tracking traffic to 404 pages using log file analysis.[21] This can be useful to understand more about what 404s users reached on the site. Another method of tracking traffic to 404 pages is using JavaScript-based traffic tracking tools.[22]
See also
- Blue screen of death
- Funky caching
- Link rot
- List of HTTP status codes
References
- ^ a b Fielding, R.; Reschke, J. (June 2014). Fielding, R; Reschke, J (eds.). «RFC 7231, HTTP/1.1 Semantics and Content, Section 6.5.4 404 Not Found». ietf.org. doi:10.17487/RFC7231. S2CID 14399078. Retrieved 13 December 2018.
- ^ Ziv Bar-Yossef; Andrei Z. Broder; Ravi Kumar; Andrew Tompkins (2004). Sic Transit Gloria Telae: Towards an Understanding of the Web’s Decay. Proceedings of the 13th International Conference on World Wide Web (WWW). pp. 328–337. doi:10.1145/988672.988716. ISBN 978-1581138443. S2CID 587547.
- ^ «Why is your crawler asking for strange URLs that have never existed on my site?». Yahoo Ysearch Help page. Archived from the original on 15 July 2014. Retrieved 4 September 2013.
- ^ «Farewell to soft 404s». Google Official Blog. Retrieved 20 September 2008.
- ^ «LINX Public Affairs » Cleanfeed: the facts». Publicaffairs.linx.net. 10 September 2004. Archived from the original on 13 May 2011. Retrieved 6 March 2011.
- ^ «DEMON – Error 403». Retrieved 14 June 2012.
- ^ Sambandaraksa, Don (18 February 2009). «The old fake ‘404 Not Found’ routine — Dead link». Bangkok Post. Retrieved 12 September 2010.
- ^ Noman, Helmi (12 September 2008). «Tunisian journalist sues government agency for blocking Facebook, claims damage for the use of 404 error message instead of 403». Open Net Initiative. Retrieved 21 November 2010.
- ^ «Anti-censorship movement in Tunisia: creativity, courage and hope!». Global Voices Advocacy. 27 May 2010. Retrieved 28 August 2010.
- ^ «Friendly HTTP Error Pages». msdn.com. 18 August 2010. Archived from the original on 2 December 2010. Retrieved 14 June 2012.
- ^ «Issue 1695: Chrome needs option to turn off «Friendly 404″ displays». bugs.chromium.org. Retrieved 25 December 2021.
- ^ Heng, Christopher (7 September 2008). «What is Favicon.ico and How to Create a Favicon Icon for Your Website». The Site Wizard. Retrieved 23 February 2011.
- ^ «The Dastardly «favicon.ico not found» Error». Internet Folks. 3 August 1999.
- ^ «From skateboarding bears to missing children: The power of the 404 Not Found error page». Metro. 6 June 2011. Retrieved 16 April 2013.
- ^ «The political Page 404 war». BBC Newsbeat. 27 April 2015. Retrieved 18 May 2018.
- ^ «Notfound.org». notfound. notfound. Archived from the original on 2 September 2014.
- ^ «Missing children messages go on 404 error pages». BBC News. 27 September 2012. Retrieved 20 September 2014.
- ^ Swenson, Sahala (19 August 2008). «Make your 404 pages more useful». Official Google Webmaster Central Blog. Google, Inc. Retrieved 28 August 2009.
- ^ «Sources Leading To 404s». SpringTrax. Retrieved 11 February 2013.
- ^ Cushing, Anne (2 April 2013). «A Data-Centric Approach To Identifying 404 Pages Worth Saving». Search Engine Land. Retrieved 7 June 2013.
- ^ «Tracking and Preventing 404 Errors». 404errorpages.com. Retrieved 7 June 2013.
- ^ «Understand 404 Errors». SpringTrax.com. Retrieved 7 June 2013.
External links
- A More Useful 404
- 404 Not Found of the Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content specification, at the Internet Engineering Task Force
- ErrorDocument Directive – instructions on custom error pages for the Apache 2.0 web server
- 404: Not Found – an award-winning song about the error code
Пользователь — человек привередливый во многих отношениях. В том числе, привередливый к поиску нужной ему информации. Интернет открывает для нас множество дверей, за которыми скрывается массив данных, необходимых услуг и прочее. Любое слово, изображение, неверно расположенная кнопочки может спугнуть его. Что уж говорить о странице ошибки 404. Даже самый пытливый ум стремиться как можно скорее закрыть эту страницу и перейти к другому сайту. Почему? Потому что сложно и ресурсозатратно… И что остается владельцу сайта? Как красиво преподнести ошибку, чтобы у пользователя осталось только приятное впечатление и желание подробнее ознакомиться с вашим ресурсом?
Коротко напомню о том, что такое ошибка 404 и с чем её едят
404 Page Not Found (она же – ошибка 404 или «страница не найдена») – это код состояния, в котором пребывает HTTP. Для самых любопытных: первая цифра кода “4” – обозначение неточности со стороны пользователя, а именно неверно введенный URL или попытка открыть уже/ещё несуществующую страницу; код “04” – тот самый “Not Found”, а именно вполне конкретная ошибка.
Почему данная страница “неожиданно” появляется перед пользователем?
- Сайт удален и больше не работает. В этом случае вам, как владельцу, переживать не о чем, если только у вас не появился новый сайт, до которого пользователь ещё не дошёл;
- Сайт находится в разработке. Тут необходимо красиво подойти к “диалогу” с пользователем и уведомить его о том, что в скором времени он может вернуться. Главное, сделать это так, чтобы ему захотелось это сделать;
- Проблема в написании ссылки;
- URL страницы изменился.
Рассмотрим 404 ошибку глазами обычного посетителя
Первый вопрос, который приходит на ум, когда всплывает неопознанная ошибка: «Что мне со всем этим дальше делать?». Если решения на горизонте не видно, проще всего попрощаться со страницей и открыть другую. Но! Это лишь в том случае, если не будет чего-то интересного, что смогло бы меня удержать. Вполне очевидное решение — сделать эту страницу интересной и не вызывающей отторжения.
“Авторская” страница ошибки 404 должна выполнять всего несколько функций:
- иметь красивый вид, не отпугивать внимание и заинтересовывать;
- отвечать на тот самый вопрос “И что же мне делать дальше?”;
- включать в себя работу SEO.
«Чек-лист» дружелюбной ошибки
Приведем что-то вроде «Чек-листа» для создания дружелюбной страницы, сообщающей пользователю о том, что «что-то пошло не так»:
- Будьте открытыми и готовыми помочь пользователю справиться с ошибкой, с которой он столкнулся не по своей вине.
- Не нужно заумничать и вдаваться в техническое объяснение ошибки. Как минимум, это совершенно непонятно «непосвященном», максимум – раздражает непонятностью. Не обязательным становится даже употребление цифр “404”, главное просто и доступно объяснить, по какой причине пользователь мог оказаться “здесь” и “сейчас”.
- Объясните, что нужно сделать. Например, проверить адрес ссылки.
- Не забывайте про стиль вашего сайта. Так у пользователя заранее будет сформировано доверительное отношение к странице, потому что стиль “ошибки” будет знаком.
- Принимая всё вышеперечисленное, не нужно пичкать страницу большим количеством текста, ссылками, изображениями. Это страница ошибки, страница, которая “не найдена”, но никак не одна из нормальных страниц сайта.
- Будьте изобретательными и позитивными. Самый лучший способ удержать пользователя на страницах своего сайта — привлечь его внимание. Лучше всего с этим справляется забавное, иногда каламбурное, оформление.
- Всегда выручает строка поиска, которая:
А.удержит пользователя;
Б.поможет ему всё-таки отыскать то, что он искал.
- Не забывайте про SEO. Максимально важно сократить, а в лучшем случае — вовсе исключить появление некорректных URL, приводящих к ошибке 404
- И вашим, и нашим. Дайте пользователю возможность сообщить о трудностях, с которыми ему пришлось столкнуться. Например, предложите ему нажать перейти на главную страницу по этой кнопке, тем самым сообщив об ошибке.
На примерах
Приведу примеры самых приятных ошибок, которые приходилось встречать.
В статье мы расскажем, что означает ошибка 404 на сайте. Также она может называться:
- 404 page not found,
- http error 404,
- error 404.
Ниже мы опишем, почему возникает ошибка 404, а также как её отследить и исправить.
404 ошибка (http error 404) — что это значит?
Ошибка 404 page not found — это код ответа сервера. Что это значит?
Когда вы вводите адрес сайта, браузер запрашивает его стартовую страницу у сервера. Если сервер не может найти страницу, он сообщает об этом браузеру с помощью кода 404. Это сообщение отображается на экране пользователя в браузере.
Почему такое может произойти? Есть несколько возможных причин:
- Вы допустили ошибку при вводе адреса страницы или при открытии файла в браузере. Или браузеру не удалось найти IP-адрес сервера. Сервер не может найти и выдать данные потому, что вы дали ему неправильные «координаты». В таком случае вам достаточно просто исправить ошибку в URL-адресе, и вместо страницы с ошибкой 404 появятся искомые страница/файл.
- Данные (страница или файл) не размещены на сервере, или CMS неверно отвечает на запрос пользователя. В этом случае дело обстоит сложнее и быстро справиться с проблемой не получится. Чтобы устранить ошибку 404, определите, как создавался сайт, на котором обнаружена ошибка (на CMS или без использования CMS). От этого будет зависеть способ решения проблемы.
Мы рассмотрим, что делать с ошибкой 404 и как исправить.
Как убрать ошибку 404 на сайте, созданном на CMS (WordPress, Joomla, 1С-Битрикс и т.д.)
На сайтах, созданных с использованием CMS, встречаются различные страницы с ошибкой 404 (http status 404). В зависимости от типа страницы с ошибкой различаются причины возникновения и пути решения проблемы:
- Если вы видите на своём сайте стандартную ошибку 404 REG.RU:
В большинстве случаев проблема связана с отсутствием конфигурационного файла .htaccess. Как избавиться от ошибки 404? Создайте в корневой папке сайта пустой текстовый файл с расширением .htaccess и добавьте в него стандартные директивы для используемой CMS. Стандартные директивы приведены в статье: Файлы .htaccess для популярных CMS.
Важно: в панели управления cPanel файл .htaccess по умолчанию скрыт (т.е. он существует, но не виден). Следуйте инструкции, чтобы включить отображение файла. Затем сверьте его содержимое со стандартным.
Если файл .htaccess существует и его содержимое корректно, а ошибка 404 not found сохраняется, обратитесь в техническую поддержку.
- Если вы видите иную страницу ошибки, которую отдает CMS сайта. Например:
Ошибка на WordPress
Пользовательская ошибка 404 not found
Возможно, страница не создана или не опубликована на этапе размещения сайта в админке CMS. Также ошибка может быть связана с формированием «человекопонятных» ЧПУ-ссылок с помощью SEO-плагинов. Чтобы избавиться от проблемы, необходимо обратиться к веб-разработчикам сайта или на тематические форумы, на которых представлена необходимая техническая информация (ошибка http 404).
Как быстро устранить ошибку 404 на сайте, созданном без использования CMS
На сайтах, созданных без использования CMS, код ошибки 404 отображается следующим образом:
Что означает это сообщение? Запрашиваемые страница/файл отсутствуют или размещены в неправильной папке (не в корневой папке сайта).
Что делать? Откройте корневую папку сайта в панели управления хостингом и проверьте, находятся ли в ней файлы вашего сайта.
- Если искомые файлы отсутствуют, следуйте инструкции: Как загрузить файл в корневой каталог сайта? После размещения файлов в корневой папке ошибка 404 должна исчезнуть.
- Если файлы существуют и находятся в корневой папке, обратитесь в техническую поддержку.
Как находить и мониторить код ошибки 404?
Если вы владелец сайта, вы можете найти страницы с ошибкой с помощью специальных сервисов. Самые популярные сервисы:
- Яндекс.Вебмастер,
- Google Search Console,
- Screaming Frog.
Ниже мы описали, как работать с каждым из них.
Яндекс.Вебмастер
-
Авторизуйтесь в Яндекс.Вебмастер.
-
Перейдите в раздел Индексирование — Страницы в поиске:
HTTP status 404 — что это
- Выберите Исключенные страницы:
- Добавьте фильтр, при котором отобразятся результаты с ошибкой «404 page not found»:
Google Search Console
-
Авторизуйтесь в Google Search Console.
-
Разверните блок Индекс и выберите Покрытие:
404 ошибка: что это
- Используйте фильтр, который покажет код ошибки 404. Для этого перейдите в раздел Сведения и кликните Отправленный URL не найден (ошибка 404):
Ошибка 404: что значит и как исправить
Screaming Frog
-
Загрузите программу с официального сайта.
-
Установите её на компьютер.
-
Откройте программу, введите ссылку на сайт и нажмите Start:
- Перейдите во вкладку Response Code. Из выпадающего списка выберите фильтр Client Error (4xx):
Открывается только главная страница сайта, на внутренних страницах ошибка 404 или 500
Рассмотрим, что значит и как исправить ошибку отображения внутренних страниц сайта (error 404 или 500). Причиной проблемы является отсутствие файла .htaccess (либо он пустой, либо в нем не хватает необходимых директив для работы CMS). Решить проблему может замена текущего файла .htaccess стандартным для данной CMS.
На хостинге Linux
Если у вас ISPmanager, проверьте, не включены ли Автоподдомены. Если они включены, отключите их, проверьте актуальность проблемы.
В остальных случаях для устранения внутренней ошибки 404 или 500, перейдите в корневую папку сайта: Как узнать корневую папку сайта
Создайте файл .htaccess (или замените его) со следующим содержимым:
Файл .htaccess для Joomla
##
# @version $Id: htaccess.txt 14401 2010-01-26 14:10:00Z louis $
# @package Joomla
# @copyright Copyright (C) 2005 - 2010 Open Source Matters. All rights reserved.
# @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
# Joomla! is Free Software
##
#####################################################
# READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE
#
# The line just below this section: 'Options +FollowSymLinks' may cause problems
# with some server configurations. It is required for use of mod_rewrite, but may already
# be set by your server administrator in a way that dissallows changing it in
# your .htaccess file. If using it causes your server to error out, comment it out (add # to
# beginning of line), reload your site in your browser and test your sef url's. If they work,
# it has been set by your server administrator and you do not need it set here.
#
#####################################################
## Can be commented out if causes errors, see notes above.
Options +FollowSymLinks
#
# mod_rewrite in use
RewriteEngine On
########## Begin - Rewrite rules to block out some common exploits
## If you experience problems on your site block out the operations listed below
## This attempts to block the most common type of exploit `attempts` to Joomla!
#
## Deny access to extension xml files (uncomment out to activate)
#<Files ~ ".xml$">
#Order allow,deny
#Deny from all
#Satisfy all
#</Files>
## End of deny access to extension xml files
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|%3D) [OR]
# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*(.*) [OR]
# Block out any script that includes a <script> tag in URL
RewriteCond %{QUERY_STRING} (<|%3C).*script.*(>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL
RewriteCond %{QUERY_STRING} GLOBALS(=|[|%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL
RewriteCond %{QUERY_STRING} _REQUEST(=|[|%[0-9A-Z]{0,2})
# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule ^(.*)$ index.php [F,L]
#
########## End - Rewrite rules to block out some common exploits
# Uncomment following line if your webserver's URL
# is not directly related to physical file paths.
# Update Your Joomla! Directory (just / for root)
# RewriteBase /
########## Begin - Joomla! core SEF Section
#
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^/index.php
RewriteCond %{REQUEST_URI} (/|.php|.html|.htm|.feed|.pdf|.raw|/[^.]*)$ [NC]
RewriteRule (.*) index.php
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
#
########## End - Joomla! core SEF Section
Файл .htaccess для WordPress
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
Файл .htaccess для HostCMS
Options +FollowSymlinks
AddDefaultCharset Off
<IfModule mod_php4.c>
php_flag magic_quotes_gpc off
php_flag magic_quotes_runtime off
php_flag register_globals off
</IfModule>
<IfModule mod_php5.c>
php_flag magic_quotes_gpc off
php_flag magic_quotes_runtime off
php_flag register_globals off
</IfModule>
<IfModule mod_dir.c>
DirectoryIndex index.php index.htm index.html
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php
</IfModule>
Файл .htaccess для Bitrix
Options -Indexes
ErrorDocument 404 /404.php
<IfModule mod_php5.c>
php_flag allow_call_time_pass_reference 1
php_flag session.use_trans_sid off
#php_value display_errors 1
#php_value mbstring.func_overload 2
#php_value mbstring.internal_encoding UTF-8
</IfModule>
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !/bitrix/urlrewrite.php$
RewriteRule ^(.*)$ /bitrix/urlrewrite.php [L]
RewriteRule .* - [E=REMOTE_USER:%{HTTP:Authorization}]
</IfModule>
<IfModule mod_dir.c>
DirectoryIndex index.php index.html
</IfModule>
<IfModule mod_expires.c>
ExpiresActive on
ExpiresByType image/jpeg "access plus 3 day"
ExpiresByType image/gif "access plus 3 day"
</IfModule>
Файл .htaccess для ModX
# MODx supports Friendly URLs via this .htaccess file. You must serve web
# pages via Apache with mod_rewrite to use this functionality, and you must
# change the file name from ht.access to .htaccess.
#
# Make sure RewriteBase points to the directory where you installed MODx.
# E.g., "/modx" if your installation is in a "modx" subdirectory.
#
# You may choose to make your URLs non-case-sensitive by adding a NC directive
# to your rule: RewriteRule ^(.*)$ index.php?q=$1 [L,QSA,NC]
RewriteEngine On
RewriteBase /
# Rewrite www.domain.com -> domain.com -- used with SEO Strict URLs plugin
#RewriteCond %{HTTP_HOST} .
#RewriteCond %{HTTP_HOST} !^example-domain-please-change.com [NC]
#RewriteRule (.*) http://example-domain-please-change.com/$1 [R=301,L]
#
# or for the opposite domain.com -> www.domain.com use the following
# DO NOT USE BOTH
#
#RewriteCond %{HTTP_HOST} .
#RewriteCond %{HTTP_HOST} !^www.example-domain-please-change.com [NC]
#RewriteRule (.*) http://www.example-domain-please-change.com/$1 [R=301,L]
#
# Rewrite secure requests properly to prevent SSL cert warnings, e.g. prevent
# https://www.domain.com when your cert only allows https://secure.domain.com
#RewriteCond %{SERVER_PORT} !^443
#RewriteRule (.*) https://example-domain-please-change.com.com/$1 [R=301,L]
#
# The Friendly URLs part
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
#
# Make sure .htc files are served with the proper MIME type, which is critical # for XP SP2. Un-comment if your host allows htaccess MIME type overrides.
#AddType text/x-component .htc
#
# If your server is not already configured as such, the following directive
# should be uncommented in order to set PHP's register_globals option to OFF.
# This closes a major security hole that is abused by most XSS (cross-site
# scripting) attacks. For more information: http://php.net/register_globals
#
# To verify that this option has been set to OFF, open the Manager and choose
# Reports -> System Info and then click the phpinfo() link. Do a Find on Page
# for "register_globals". The Local Value should be OFF. If the Master Value
# is OFF then you do not need this directive here.
#
# IF REGISTER_GLOBALS DIRECTIVE CAUSES 500 INTERNAL SERVER ERRORS :
#
# Your server does not allow PHP directives to be set via .htaccess. In that
# case you must make this change in your php.ini file instead. If you are
# using a commercial web host, contact the administrators for assistance in
# doing this. Not all servers allow local php.ini files, and they should
# include all PHP configurations (not just this one), or you will effectively
# reset everything to PHP defaults. Consult www.php.net for more detailed
# information about setting PHP directives.
#
#php_flag register_globals Off
#
# For servers that support output compression, you should pick up a bit of
# speed by un-commenting the following lines.
#
#php_flag zlib.output_compression On
#php_value zlib.output_compression_level 5
#
# The following directives stop screen flicker in IE on CSS rollovers. If
# needed, un-comment the following rules. When they're in place, you may have
# to do a force-refresh in order to see changes in your designs.
#
#ExpiresActive On
#ExpiresByType image/gif A2592000
#ExpiresByType image/jpeg A2592000
#ExpiresByType image/png A2592000
#BrowserMatch "MSIE" brokenvary=1
#BrowserMatch "Mozilla/4.[0-9]{2}" brokenvary=1
#BrowserMatch "Opera" !brokenvary
#SetEnvIf brokenvary 1 force-no-vary
Файл .htaccess для Drupal
#
# Apache/PHP/Drupal settings:
#
# Protect files and directories from prying eyes.
<FilesMatch ".(engine|inc|info|install|make|module|profile|test|po|sh|.*sql|theme|tpl(.php)?|xtmpl)$|^(..*|Entries.*|Repository|Root|Tag|Template)$">
Order allow,deny
</FilesMatch>
# Don't show directory listings for URLs which map to a directory.
Options -Indexes
# Follow symbolic links in this directory.
Options +FollowSymLinks
# Make Drupal handle any 404 errors.
ErrorDocument 404 /index.php
# Force simple error message for requests for non-existent favicon.ico.
<Files favicon.ico>
# There is no end quote below, for compatibility with Apache 1.3.
ErrorDocument 404 "The requested file favicon.ico was not found.
</Files>
# Set the default handler.
DirectoryIndex index.php index.html index.htm
# Override PHP settings that cannot be changed at runtime. See
# sites/default/default.settings.php and drupal_initialize_variables() in
# includes/bootstrap.inc for settings that can be changed at runtime.
# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
php_flag magic_quotes_gpc off
php_flag magic_quotes_sybase off
php_flag register_globals off
php_flag session.auto_start off
php_value mbstring.http_input pass
php_value mbstring.http_output pass
php_flag mbstring.encoding_translation off
</IfModule>
# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
# Enable expirations.
ExpiresActive On
# Cache all files for 2 weeks after access (A).
ExpiresDefault A1209600
<FilesMatch .php$>
# Do not allow PHP scripts to be cached unless they explicitly send cache
# headers themselves. Otherwise all scripts would have to overwrite the
# headers set by mod_expires if they want another caching behavior. This may
# fail if an error occurs early in the bootstrap process, and it may cause
# problems if a non-Drupal PHP file is installed in a subdirectory.
ExpiresActive Off
</FilesMatch>
</IfModule>
# Various rewrite rules.
<IfModule mod_rewrite.c>
RewriteEngine on
# Block access to "hidden" directories whose names begin with a period. This
# includes directories used by version control systems such as Subversion or
# Git to store control files. Files whose names begin with a period, as well
# as the control files used by CVS, are protected by the FilesMatch directive
# above.
#
# NOTE: This only works when mod_rewrite is loaded. Without mod_rewrite, it is
# not possible to block access to entire directories from .htaccess, because
# <DirectoryMatch> is not allowed here.
#
# If you do not have mod_rewrite installed, you should remove these
# directories from your webroot or otherwise protect them from being
# downloaded.
RewriteRule "(^|/)." - [F]
# If your site can be accessed both with and without the 'www.' prefix, you
# can use one of the following settings to redirect users to your preferred
# URL, either WITH or WITHOUT the 'www.' prefix. Choose ONLY one option:
#
# To redirect all users to access the site WITH the 'www.' prefix,
# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} !^www. [NC]
# RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
#
# To redirect all users to access the site WITHOUT the 'www.' prefix,
# (http://www.example.com/... will be redirected to http://example.com/...)
# uncomment the following:
# RewriteCond %{HTTP_HOST} ^www.(.+)$ [NC]
# RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]
# Modify the RewriteBase if you are using Drupal in a subdirectory or in a
# VirtualDocumentRoot and the rewrite rules are not working properly.
# For example if your site is at http://example.com/drupal uncomment and
# modify the following line:
# RewriteBase /drupal
#
# If your site is running in a VirtualDocumentRoot at http://example.com/,
# uncomment the following line:
# RewriteBase /
# Pass all requests not referring directly to files in the filesystem to
# index.php. Clean URLs are handled in drupal_environment_initialize().
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]
# Rules to correctly serve gzip compressed CSS and JS files.
# Requires both mod_rewrite and mod_headers to be enabled.
<IfModule mod_headers.c>
# Serve gzip compressed CSS files if they exist and the client accepts gzip.
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -s
RewriteRule ^(.*).css $1.css.gz [QSA]
# Serve gzip compressed JS files if they exist and the client accepts gzip.
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -s
RewriteRule ^(.*).js $1.js.gz [QSA]
# Serve correct content types, and prevent mod_deflate double gzip.
RewriteRule .css.gz$ - [T=text/css,E=no-gzip:1]
RewriteRule .js.gz$ - [T=text/javascript,E=no-gzip:1]
<FilesMatch "(.js.gz|.css.gz)$">
# Serve correct encoding type.
Header append Content-Encoding gzip
# Force proxies to cache gzipped & non-gzipped css/js files separately.
Header append Vary Accept-Encoding
</FilesMatch>
</IfModule>
</IfModule>
Файл .htaccess для NetCat
AddDefaultCharset windows-1251
ErrorDocument 404 /netcat/require/e404.php
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ /netcat/require/e404.php?REQUEST_URI=$1 [L,QSA]
</ifModule>
Файл .htaccess для DLE
DirectoryIndex index.php
RewriteEngine On
RewriteBase /
# Редиректы
RewriteRule ^page/(.*)$ index.php?cstart=$1 [L]
# Сам пост
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/page,([0-9]+),([0-9]+),(.*).html(/?)+$ index.php?subaction=showfull&year=$1&month=$2&day=$3&news_page=$4&cstart=$5&news_name=$6 [L]
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/page,([0-9]+),(.*).html(/?)+$ index.php?subaction=showfull&year=$1&month=$2&day=$3&news_page=$4&news_name=$5 [L]
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/print:page,([0-9]+),(.*).html(/?)+$ engine/print.php?subaction=showfull&year=$1&month=$2&day=$3&news_page=$4&news_name=$5 [L]
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/(.*).html(/?)+$ index.php?subaction=showfull&year=$1&month=$2&day=$3&news_name=$4 [L]
RewriteRule ^([^.]+)/page,([0-9]+),([0-9]+),([0-9]+)-(.*).html(/?)+$ index.php?newsid=$4&news_page=$2&cstart=$3&seourl=$5&seocat=$1 [L]
RewriteRule ^([^.]+)/page,([0-9]+),([0-9]+)-(.*).html(/?)+$ index.php?newsid=$3&news_page=$2&seourl=$4&seocat=$1 [L]
RewriteRule ^([^.]+)/print:page,([0-9]+),([0-9]+)-(.*).html(/?)+$ engine/print.php?news_page=$2&newsid=$3&seourl=$4&seocat=$1 [L]
RewriteRule ^([^.]+)/([0-9]+)-(.*).html(/?)+$ index.php?newsid=$2&seourl=$3&seocat=$1 [L]
RewriteRule ^page,([0-9]+),([0-9]+),([0-9]+)-(.*).html(/?)+$ index.php?newsid=$3&news_page=$1&cstart=$2&seourl=$4 [L]
RewriteRule ^page,([0-9]+),([0-9]+)-(.*).html(/?)+$ index.php?newsid=$2&news_page=$1&seourl=$3 [L]
RewriteRule ^print:page,([0-9]+),([0-9]+)-(.*).html(/?)+$ engine/print.php?news_page=$1&newsid=$2&seourl=$3 [L]
RewriteRule ^([0-9]+)-(.*).html(/?)+$ index.php?newsid=$1&seourl=$2 [L]
# За день
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})(/?)+$ index.php?year=$1&month=$2&day=$3 [L]
RewriteRule ^([0-9]{4})/([0-9]{2})/([0-9]{2})/page/([0-9]+)(/?)+$ index.php?year=$1&month=$2&day=$3&cstart=$4 [L]
# За весь месяц
RewriteRule ^([0-9]{4})/([0-9]{2})(/?)+$ index.php?year=$1&month=$2 [L]
RewriteRule ^([0-9]{4})/([0-9]{2})/page/([0-9]+)(/?)+$ index.php?year=$1&month=$2&cstart=$3 [L]
# Вывод за весь год
RewriteRule ^([0-9]{4})(/?)+$ index.php?year=$1 [L]
RewriteRule ^([0-9]{4})/page/([0-9]+)(/?)+$ index.php?year=$1&cstart=$2 [L]
# вывод отдельному тегу
RewriteRule ^tags/([^/]*)(/?)+$ index.php?do=tags&tag=$1 [L]
RewriteRule ^tags/([^/]*)/page/([0-9]+)(/?)+$ index.php?do=tags&tag=$1&cstart=$2 [L]
# вывод для отдельного юзера
RewriteRule ^user/([^/]*)/rss.xml$ engine/rss.php?subaction=allnews&user=$1 [L]
RewriteRule ^user/([^/]*)(/?)+$ index.php?subaction=userinfo&user=$1 [L]
RewriteRule ^user/([^/]*)/page/([0-9]+)(/?)+$ index.php?subaction=userinfo&user=$1&cstart=$2 [L]
RewriteRule ^user/([^/]*)/news(/?)+$ index.php?subaction=allnews&user=$1 [L]
RewriteRule ^user/([^/]*)/news/page/([0-9]+)(/?)+$ index.php?subaction=allnews&user=$1&cstart=$2 [L]
RewriteRule ^user/([^/]*)/news/rss.xml(/?)+$ engine/rss.php?subaction=allnews&user=$1 [L]
# вывод всех последних новостей
RewriteRule ^lastnews/(/?)+$ index.php?do=lastnews [L]
RewriteRule ^lastnews/page/([0-9]+)(/?)+$ index.php?do=lastnews&cstart=$1 [L]
# вывод в виде каталога
RewriteRule ^catalog/([^/]*)/rss.xml$ engine/rss.php?catalog=$1 [L]
RewriteRule ^catalog/([^/]*)(/?)+$ index.php?catalog=$1 [L]
RewriteRule ^catalog/([^/]*)/page/([0-9]+)(/?)+$ index.php?catalog=$1&cstart=$2 [L]
# вывод непрочитанных статей
RewriteRule ^newposts(/?)+$ index.php?subaction=newposts [L]
RewriteRule ^newposts/page/([0-9]+)(/?)+$ index.php?subaction=newposts&cstart=$1 [L]
# вывод избранных статей
RewriteRule ^favorites(/?)+$ index.php?do=favorites [L]
RewriteRule ^favorites/page/([0-9]+)(/?)+$ index.php?do=favorites&cstart=$1 [L]
RewriteRule ^rules.html$ index.php?do=rules [L]
RewriteRule ^statistics.html$ index.php?do=stats [L]
RewriteRule ^addnews.html$ index.php?do=addnews [L]
RewriteRule ^rss.xml$ engine/rss.php [L]
RewriteRule ^sitemap.xml$ uploads/sitemap.xml [L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^.]+)/page/([0-9]+)/$ index.php?do=cat&category=$1&cstart=$2 [L]
RewriteRule ^([^.]+)/$ index.php?do=cat&category=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)/rss.xml$ engine/rss.php?do=cat&category=$1 [L]
RewriteRule ^page,([0-9]+),([^/]+).html$ index.php?do=static&page=$2&news_page=$1 [L]
RewriteRule ^print:([^/]+).html$ engine/print.php?do=static&page=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]+).html$ index.php?do=static&page=$1 [L]
Файл .htaccess для Opencart
Options +FollowSymlinks
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]
Файл .htaccess для Webasyst
<FilesMatch ".md5$">
Deny from all
</FilesMatch>
DirectoryIndex index.php
Options -Indexes
# Comment the following line, if option Multiviews not allowed here
Options -MultiViews
AddDefaultCharset utf-8
<ifModule mod_rewrite.c>
RewriteEngine On
# Uncomment the following line, if you are having trouble
RewriteBase /
RewriteCond %{REQUEST_URI} !.(js|css|jpg|jpeg|gif|png|svg|ttf|eot|otf|woff|woff2)$ [or]
RewriteCond %{REQUEST_URI} apple-touch-icon.png$ [or]
RewriteCond %{REQUEST_METHOD} ^(POST|PUT|COPY|MOVE|DELETE|PROPFIND|OPTIONS|MKCOL)$ [or]
RewriteCond %{HTTP:Translate} ^.+$ [or]
RewriteCond %{HTTP_USER_AGENT} ^(DavClnt|litmus|gvfs|davfs|wdfs|WebDAV|cadaver|Cyberduck)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [L,QSA]
</ifModule>
<ifModule mod_headers.c>
<FilesMatch ".(jpg|jpeg|png|gif|js|css|svg|ttf|eot|otf|woff|woff2)$">
Header set Cache-Control "max-age=3153600, public"
</FilesMatch>
</ifModule>
Если у вас хостинг Windows
На хостинге Windows файл .htaccess не поддерживается. Его функцию выполняет файл web.config. Если вы наблюдаете внутреннюю ошибку 404 или 500 на хостинге Windows, рекомендуем обратиться к разработчикам сайта или на тематические форумы с вопросом, как убрать 404, заменив файл web.config.
Что будет, если не исправлять ошибку 404
Во-первых, есть риск потерять потенциальных клиентов. Когда пользователь не получает информацию, которую искал, он уходит на другой сайт, который ему предложил браузер. Если ошибка встречается на веб-ресурсе часто, можно потерять и уже имеющихся пользователей, так как они решат, что использование такого сайта небезопасно.
Во-вторых, есть риск потерять хорошую позицию в поисковой выдаче. Сама по себе страница с ошибкой 404 не вызывает у поисковой системы недоверия. Она просто удаляется из индексации. Однако там могли находиться ключевые слова, которые могли повлиять положительно на поисковую выдачу. Если на сайте много страниц с ошибкой, тогда поисковые роботы действительно могут отнестись с недоверием ко всему веб-ресурсу и сайт может потерять высокий рейтинг.
Сделайте страницу 404 полезной
Ошибка 404 (страница не найдена) может появиться в любое время. Важно, чтобы пользователь при входе на эту страницу не потерял доверия к сайту. Страницы с ошибкой 404 можно создавать самостоятельно. Например, если у вас сайт на WordPress или вы пользуетесь услугой REG.Site, страницу с ошибкой можно легко создать с помощью плагина 404page.
Вот несколько советов по созданию страницы:
- дизайн этой страницы должен соответствовать всему ресурсу (цвет, шрифт, иллюстрации),
- поместите ссылку на главную страницу,
- добавьте дайджесты последних публикаций на сайте,
- поместите контакты организации (номер телефона, адрес) и службы поддержки,
- можно предложить действия для решения проблемы доступа к странице.
После посещения такой страницы посетитель хоть и не получит нужную информацию, однако у него останется положительное впечатление от посещения сайта, и в следующий раз он не откажется зайти на него снова.
Если перечисленные способы не помогли исправить ошибку, обратитесь в службу поддержки REG.RU.
Видеосправка. Об ошибке 404 и как создать страницу для неё
Читайте о самых распространённых онлайн ошибках. Какие причины их возникновения и как исправить.
Введение
В пользование сетью «Интернет» вовлечено подавляющее большинство всех обладателей компьютерной техники, независимо от вида используемых образцов устройств. И несмотря на многие преимущества задействования «Интернета» как для обработки и хранения данных, так и для их распространения и обмена, в некоторых случаях существует вероятность столкнуться с отказом в доступе к тем или иным ресурсам сети по причине возникновения разнообразных видов ошибок. И несмотря на утверждение, что полностью избежать ошибок в целом при взаимодействии с данными в сети «Интернет» практически невозможно, пользователи могут ознакомиться со списком основных и часто встречающихся видов ошибок, понять их значение и изучить некоторые основные шаги для их устранения. И далее в нашей статье мы подробнее остановимся на освещении данных вопросов.
Распространенные типы сетевых ошибок при доступе к ресурсам сети «Интернет»
Большинство известных видов ошибок в сети «Интернет» сопровождаются кодом состояния «HTTP». Обычно пользователи могут наблюдать сообщение об ошибке, содержащее помимо объясняющего текста еще числовое значение формата «4XX» или «5XX» (за числами четыре или пять следуют две дополнительные цифры, например, код ошибки имеет вид «404»).
И вариант формата «4XX», и «5XX» являются ошибками, но они имеют существенную разницу. Формат «4XX» – это ошибки, возникающие вследствие деятельности клиента, а «5XX» – результат ошибки сервера. Если при обращении к сетевому ресурсу всплывает сообщение с ошибкой в виде «4XX», то, скорее всего, пользователи могут ее самостоятельно исправить.
Ошибки вида «5XX» – это ошибки сервера, которые означают, что пользователи не оказывали влияния на результат, приведший к возникновению ошибки, и источником сбоя является неработающий сервер, к которому пользователи пытаются получить доступ. Независимо от вида ошибки, связанна ли она с деятельностью пользователей или работоспособностью удаленного сетевого сервера, пользователи могут предпринять несколько шагов, которые могут помочь решить проблему и устранить существующую неисправность.
В последующих разделах мы постарались перечислить наиболее распространенные сетевые ошибки, с которыми могут сталкиваться пользователи при взаимодействии с ресурсами сети «Интернет», а также упомянули пару полезных решений для исправления каждой ошибки. Пользователи не могут решить все онлайн-ошибки, так как некоторые из них происходят по вине серверов, и с ними мало что можно поделать для успешного восстановления работоспособности. Тем не менее, в ряде случаев, стоит попробовать устранить возникшую ошибку.
«400 Bad Request» («ошибка неверного запроса»)
Каждый раз, когда пользователи пытаются открыть веб-сайт путем набора «URL-адреса» в адресной строке сетевого обозревателя или нажимают на соответствующую ссылку сайта, полученную посредством различных приложений, веб-браузер инициирует запрос и отправляет его на удаленный сервер веб-сайта, к которому пользователи организовывают соответствующее обращение и стараются получить доступ. Ошибка «400» возникает, когда сервер не может полноценно понять и корректно обработать запрос. Такой вид непредвиденной ошибки может произойти, если указанный запрос искажен, неверен, испорчен или поврежден, но, чаще всего, ошибка возникает по довольно простой причине, например, пользователь использовал «URL-адрес» веб-сайта, которого не существует.
В большинстве случаев пользователи самостоятельно могут решить возникшую проблему и далее представлено несколько простых способов, которые можно задействовать для исправления указанной ошибки.
Обновите страницу. Нажатие клавиши «F5» обновляет страницу в большинстве браузеров. Если проблема связана с поврежденным запросом, то его повторная отправка иногда может помочь. Процесс не займет много времени и его всегда стоит попробовать. Ошибка «400» часто является временной, и простое обновление способно нередко ее исправить.
Перепроверьте «URL- адрес». Иногда неверный «URL-адрес», указанный пользователем в адресной строке обозревателя, может вызвать ошибку «400 Bad Request» вместо ошибки «404 Not Found» (о которой мы также поговорим в одном из разделов). Просмотрите и исправьте адрес при необходимости.
Произведите поиск страницы на сайте. Возможно, ошибка в названии веб-страницы искомого сайта была допущена самим пользователем или непосредственно неверный адрес был указан в ссылке, с которой осуществлен переход на страницу. Но если страница на сайте существует, то можно в строке поиска веб-сайта указать части полного адреса страницы, чтобы получить к ней доступ через поисковую панель.
Очистите файлы «cookie» и содержимое кэша используемого веб-браузера. Иногда, при обращении к веб-сайту, от сервера возвращается ответ с ошибкой «400», потому что происходит попытка прочесть «cookie» на пользовательском компьютере, которые повреждены или сильно устарели, или, как вариант, браузер кэшировал поврежденную версию страницы, которую пользователь пытается открыть. Своевременная очистка данных кэша и файлов «cookie» может помочь исправить неприятную ошибку.
«403 Forbidden» (ошибка «запрещено»)
Ошибка «403» возникает при попытке доступа к странице или сетевому ресурсу, к которым у пользователя нет соответствующего разрешения. В большинстве случаев, устранить проблему запрета доступа силами конкретного пользователя не получиться. Обычно подобное сообщение об ошибке возникает по одной из двух причин. В первом случае, владельцы веб-сервера корректно настроили права доступа, а пользователь действительно не обладает соответствующими допусками для перехода на удаленный ресурс. В другом случае, причина заключается в том, что собственники веб-сервера неправильно настроили разрешения (случайно или преднамеренно), и пользователь получает отказ в доступе, когда он действительно необходим, даже при наличии необходимых привилегий.
Несмотря на тот факт, что ошибка «403», ограничивающая доступ к удаленному ресурсу, регулируется и управляется настройками сетевого веб-сервера, пользователи могут опробовать несколько шагов для ее исправления.
Обновите страницу. Нажатие клавиши «F5» во многих популярных обозревателях позволяет мгновенно обновить страницу.
Повторно проверьте «URL- адрес». Иногда неверно заданный в строке обозревателя «URL-адрес» может вызвать появление ошибки запрета доступа «403 Forbidden». Убедитесь, что «URL-адрес» действительно указывает на страницу, а не на каталог. Большинство веб-сайтов ограничивают доступ к своим внутренним папкам из соображений безопасности, и опечатка в адресе может быть причиной отображения ошибки «403».
Проверьте собственные разрешения. Некоторые веб-сайты ограничивают доступ к своему содержимому, разрешая удаленное обращение только зарегистрированным участникам или пользователям, обладающим определенным уровнем привилегированного доступа. Если вход в систему не был осуществлен или у пользователей нет соответствующих разрешений, то, скорее всего, система выдаст ошибку «403 Forbidden».
«404 Not Found» (ошибка «не найдено»)
Ошибка «404 Not Found» – самая распространенная ошибка в сети, которая возникает при попытке посетить несуществующую веб-страницу. В основном, данная ошибка подразумевает, что серверу не удалось найти, искомый пользователями, удаленный ресурс. В большинстве случаев, в обозревателе появится сообщение об ошибке «404» после неудачной попытки ввести «URL» искомой страницы или перейти по соответствующей ссылке, которая на сервере абсолютно не представлена. И если пользователи сталкиваются с ошибкой «404», то можно попробовать ее исправить несколькими способами.
Обновите проблемную страницу. Нажатие клавиши «F5» инициирует обновление страницы в подавляющем большинстве современных веб-браузеров. Не всегда такое решение сможет устранить ошибку «404». Но иногда, на веб-серверах может происходить случайный сбой и, как следствие, отображение страницы, которая действительно существует, будет временно приостановлено. Поэтому необходимо обязательно опробовать данный способ и перегрузить страницу, в особенности, если на обновление будет потрачено всего несколько секунд, но существует шанс добиться корректной загрузки.
Убедитесь в правильности «URL- адреса». Неверно введенные «URL-адреса» (независимо от того, была ли допущена ошибка в процессе набора или веб-страница содержит неверную ссылку) являются наиболее частой причиной отображения в обозревателе сообщения об ошибке «404 Not Found».
Осуществите поиск требуемой страницы на сайте. Возможно пользователи получили неверный «URL-адрес» или на веб-сайте, с которого был осуществлен переход, указана ошибочная ссылка, но страница на искомом ресурсе существует. Попробуйте найти, посредством использования возможностей поисковой панели сайта, «URL» требуемой страницы по названию.
«500 Internal Server Error» («внутренняя ошибка сервера»)
Если пользователь пытается посетить веб-сайт и на странице веб-браузера всплывает сообщение «500 Internal Server Error», это обычно означает, что на сетевом ресурсе, к которому непосредственно происходит обращение, существует определенная неполадка и сервер не может предоставить более конкретную информацию. Проблема относится только к сайту и никак не связана с настройками и функционированием пользовательского веб-браузера, персонального компьютера или задействованным способом подключения к сети «Интернет».
Как и в случае с другими проблемами, которые мы обсуждали ранее, пользователь можете попытаться решить возникшую неисправность лишь несколькими способами.
Обновите страницу обращения. Большинство распространенных веб-браузеров используют стандартный набор клавиш для быстрого исполнения списка команд, и нажатие на клавишу «F5» позволяет сразу обновить активную страницу. К сожалению, во многих случаях, данный способ не работает по причине неисправности на удаленном ресурсе.
Важное замечание. Не пытайтесь перезагрузить страницу, если перед получением данного сообщения об ошибке «500» была предпринята попытка осуществить онлайн-платеж или любой вид денежного перевода. Принудительное обновление страницы может привести к отправке одного и того же платежа дважды. Большинство веб-сайтов обладают встроенным инструментом защиты и должны препятствовать повторному переводу денежных средств, но проблема может возникнуть, если веб-сайт испытывает проблему во время выполнения платежа.
Обратитесь к ресурсу позже. Довольно часто проблемы с сервером носят временный характер. Попробуйте посетить страницу после небольшого перерыва.
Свяжитесь с администрацией сайта. Если проблема не устранена, попробуйте, при возможности, связаться со службой поддержки веб-сайта, и сообщить им о возникших неполадках.
«502 Bad Gateway» («ошибка шлюза»)
Ошибка «502 Bad Gateway» означает, что посещаемый вами сервер пытался получить некоторую информацию с другого сервера, но получил неверный ответ. Причиной могут послужить несколько факторов. Возможно, сервер перегружен или возникли неполадки с сетью между двумя серверами, что носит временный характер, и может быть быстро исправлено. Также, как вариант, могут оказывать влияние на отсутствие доступа неправильные настройки брандмауэра или даже ошибка кодирования. В довольно редких случаях ошибка может возникать из-за проблемы на пользовательском компьютере или сетевом оборудовании. Поэтому стоит попробовать применить несколько шагов для возможного исправления ситуации.
Обновите страницу после отображения сообщения об ошибке. Как и в предыдущих случаях, воспользуйтесь быстрым способом перезагрузки страницы посредством нажатия в веб-браузере клавиши «F5».
Проверьте, доступен ли сайт для других пользователей. Посетите сайт, такой как «IsItDownRightNow» или «DownforEveryoneorJustMe», который отслеживает состояние веб-сайтов и проверяет их работоспособность для уточнения данных, испытывают ли другие пользователи трудности с доступом к конкретному ресурсу, или проблемы возникают только локально на пользовательском устройстве.
Попробуйте получить доступ к веб-сайту позже. Возможно, проблема с сервером носит временный характер, и спустя некоторое время полноценная функциональность ресурса будет восстановлена. Поэтому попробуйте обратиться к сайту позже через некоторое время.
Выполните очистку «cookie» и содержимого кэша пользовательского браузера. Иногда (хотя и редко) серверы возвращают ошибки формата «502», потому что веб-браузер, который регулярно использует пользователь для выхода в сеть «Интернет», кэшировал устаревшие или поврежденные файлы. Процедура очистки содержимого кэша и файлов «cookie» может помочь исправить ошибку.
«503 Service Unavailable» (ошибка «сервис недоступен»)
Ошибка «503 Service Unavailable» означает, что сервер временно не может обработать запрос пользователя. Ошибка может возникать по ряду причин, но наиболее распространенная, из доступного списка вариантов, состоит в том, что сервер перегружен внешними запросами. Отображение данной ошибки на странице веб-браузера после обращения пользователя фактически означает, что с сервером все в порядке, его работоспособность не нарушена и он может обработать ваш запрос, но чрезмерная нагрузка не позволяет этого сделать в данный момент. Подобно всем ошибкам формата «5XX», ошибка «503» происходит на сервере, и, следовательно, с пользовательским компьютером все в порядке, и он не влияет на ее наличие.
Но несмотря на удаленную форму неисправности, можно попробовать применить несколько способов для устранения ошибки.
Обновите страницу с сообщением об ошибке. Нажмите на клавишу «F5» и принудительно обновите проблемную страницу (стандартный способ перезагрузки поддерживается многими основными веб-браузерами).
Проверьте работоспособность ресурса. Перейдите в веб-браузере на сайт проверки состояния удаленных ресурсов, например, «IsItDownRightNow» или «DownforEveryoneorJustMe», и оцените его доступность для других пользователей.
Попробуйте выполнить переход на сайт позже. Проблемы с сервером часто бывают временными. В частности, при отображении сообщения с ошибкой «503», велика вероятность, что сервер перегружен запросами и не может обработать все входящие обращения, который он получает. Попробуйте посетить страницу еще раз позже через некоторое время.
Полную версию статьи со всеми дополнительными видео уроками смотрите в источнике. Если у вас остались вопросы, задавайте их в комментариях.
Данный материал является частной записью члена сообщества Club.CNews.
Редакция CNews не несет ответственности за его содержание.

