Своя страница для 403 ошибки

Веб разработка » Веб-технологии 25 Янв 2012, 14:03

(Всего: 19 438, сегодня: 1 )

Выше показан пример стандартной обработки 403-й ошибки браузером, которая означает, что доступ в определенную директорию сайта заблокирован через http-запрос, а 404-я ошибка выглядит еще более скудной.

В большинство CMS встроены варианты перенаправления посетителей в случае отсутствия страниц или запрета доступа к ним. Вот на этом сайте к примеру такой вариант:

Довольно забавно и самое главное — посетитель остается на сайте, не на отдельной, специально разработанной для таких ошибок странице, а именно внутри сайта.

Я когда то заинтересовался данными редиректами и освоил эту систему. у меня был статический сайт на php-каркасе(футер,хэдр). Вот такая же ошибка на моем тестовом сайтике на локальном сервере:

Для 404–й такая же, но по другому правилу редиректа и с другим текстом для 403-й ошибки!

Htaccess

Создать файл .htaccess (точка впереди обязательна и никакого формата. Точка и хтацес)

Открыть блокнотом и написать две строчки:

ErrorDocument 403 http://art.test1.ru/error403.php
ErrorDocument 404 http://art.test1.ru/error404.php

Заменить адрес сайта на свои и адреса страниц также на свои

Страницы ошибок

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

5

19

Все уже наверно сталкивались с ситуацией, когда при посещении какого-либо сайта выскакивает надпись
Forbidden You don’t have permission to access on this server и нужный сайт не загружается.

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

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

Своя собственная страничка 403 может быть полезна для тех, кто хочет знать, прекратились ли обращения к
страницам сайта с забаненных IP адресов или нет, и кто пытается получить доступ к файлам с ограниченным доступом.

Для начала, давайте посмотрим, как выглядит исходный код странички, которая появляется при попытке доступа к
файлу .htaacces:

HTML код:

<!DOCTYPE html>
<
html lang="en"><head>
<
title>403 Forbidden</title>
</
head><body>
<
h1>Forbidden</h1>
<
p>You don't have permission to access /.htaacces
on this server.</p>
</body></html>

Для создания своей собственной странички 403, создайте файл (например, error403.php). Внутрь данного файла поместите выше
приведенный HTML код с сообщением, после которого добавьте PHP код, который будет писать логи:

PHP код:

<?php
if (filesize("logs_403.txt")<99999) {
 
$fh=fopen("logs_403.txt","a+");
 
flock($fh,LOCK_EX);
 
fseek($fh,0);
 while (!
feof($fh)) $str.=fread($fh,8192);
 
$str.=date("H:i:s d m Y")." | ".htmlspecialchars($_SERVER['REMOTE_ADDR']." | ".
 
$_SERVER['HTTP_USER_AGENT']." | ".$_SERVER['REQUEST_URI']."rn");
 
ftruncate($fh,0);
 
fwrite($fh,$str);
 
flock($fh,LOCK_UN);
 
fclose($fh);
}
?>

Для того чтобы страничка 403 стала универсальной и выдавала в сообщение URL, к которому закрыт доступ,
в HTML коде замените строчку <p>You don’t have permission to access /.htaacces на
<p>You don’t have permission to access /<?php echo strtok(basename($_SERVER[‘REQUEST_URI’]), ‘?’).’ ‘;?>

Теперь Вам остается лишь перенаправить посетителя со стандартной странички 403 на Вашу собственную.
Для этого в файле .htaccess добавьте всего одну строчку:

Цитата:

ErrorDocument 403 /error403.php

Все. Теперь все IP адреса, доступ которым запрещен на сайт и IP адреса, которые пытаются получить доступ к защищенным
ресурсам сайта, будут попадать в файл логов logs_403.txt с указанием времени, User_Agent-а и URL, по которому они пытались получить доступ.

Обращаем Ваше внимание на то, что мы специально добавили в PHP код дополнительное условие проверки
if (filesize(«logs_403.txt»)<99999) для того, чтобы при быстром росте размера файла логов и превышении им
размера в 99999 байт, логи в файл перестали записываться для снижения нагрузки на сервер.

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

Дата создания: 16:12:47 13.06.2013 г.

Посещений: 7908 раз(а).

Перед публикацией все комментарии проходят обязательную модерацию!

Если Вы хотите задать какой-либо вопрос, то сделайте это на нашем форуме.
Таким образом, Вы сможете быстрее получить ответ на интересующий Вас вопрос.

I know you can send a header that tells the browser this page is forbidden like:

header('HTTP/1.0 403 Forbidden');

But how can I also display the custom error page that has been created on the server for this type of error?

By default, just sending the header displays a white page, but I remember a while back reading that you can use the customer error page. Does anybody know?

alex's user avatar

alex

477k200 gold badges877 silver badges980 bronze badges

asked Feb 21, 2011 at 2:16

NightHawk's user avatar

0

Just echo your content after sending the header.

header('HTTP/1.0 403 Forbidden');

echo 'You are forbidden!';

forbidden

answered Feb 21, 2011 at 2:21

alex's user avatar

alexalex

477k200 gold badges877 silver badges980 bronze badges

3

http_response_code was introduced in PHP 5.4 and made the things a lot easier!

http_response_code(403);
die('Forbidden');

answered Apr 25, 2017 at 14:44

Marcio Mazzucato's user avatar

Marcio MazzucatoMarcio Mazzucato

8,7618 gold badges64 silver badges78 bronze badges

Include the custom error page after changing the header.

showdev's user avatar

showdev

28.3k37 gold badges53 silver badges72 bronze badges

answered Feb 21, 2011 at 2:30

Ibrahim AshShohail's user avatar

3

For this you must first say for the browser that the user receive an error 403. For this you can use this code:

header("HTTP/1.1 403 Forbidden" );

Then, the script send «error, error, error, error, error…….», so you must stop it. You can use

exit;

With this two lines the server send an error and stop the script.

Don’t forget : that emulate the error, but you must set it in a .htaccess file, with

ErrorDocument 403 /error403.php

Justine Krejcha's user avatar

answered Apr 18, 2013 at 17:26

Pyrrha's user avatar

PyrrhaPyrrha

2112 silver badges2 bronze badges

0

Seen a lot of the answers, but the correct one is to provide the full options for the header function call as per the php manual

void header ( string $string [, bool $replace = true [, int $http_response_code ]] )

If you invoke with

header('HTTP/1.0 403 Forbidden', true, 403);

the normal behavior of HTTP 403 as configured with Apache or any other server would follow.

answered Dec 11, 2016 at 4:24

Jiju Thomas Mathew's user avatar

I have read all the answers here and none of them was complete answer for my situation (which is exactly the same in this question) so here is how I gathered some parts of the suggested answers and come up with the exact solution:

  1. Land on your server’s real 403 page. (Go to a forbidden URL on your server, or go to any 403 page you like)
  2. Right-click and select ‘view source’. Select all the source and save it to file on your domain like: http://domain.com/403.html
  3. now go to your real forbidden page (or a forbidden situation in some part of your php) example: http://domain.com/members/this_is_forbidden.php
  4. echo this code below before any HTML output or header! (even a whitespace will cause PHP to send HTML/TEXT HTTP Header and it won’t work)
    The code below should be your first line!

        <?php header('HTTP/1.0 403 Forbidden');
        $contents = file_get_contents('/home/your_account/public_html/domain.com/403.html', TRUE);
        exit($contents);
    

Now you have the exact solution. I checked and verified with CPANEL Latest Visitors and it is registered as exact 403 event.

answered Oct 6, 2015 at 18:00

Tarik's user avatar

TarikTarik

4,23037 silver badges35 bronze badges

4

.htaccess

ErrorDocument 403     /403.html

answered Feb 21, 2011 at 2:31

6

To minimize the duty of the server make it simple:

.htaccess

ErrorDocument 403 "Forbidden"

PHP

header('HTTP/1.0 403 Forbidden');

die(); // or your message: die('Forbidden');

Shahrokhian's user avatar

answered Feb 5, 2014 at 21:34

virtual_cia's user avatar

Use ModRewrite:

RewriteRule ^403.html$ - [F]

Just make sure you create a blank document called «403.html» in your www root or you’ll get a 404 error instead of 403.

answered Feb 1, 2015 at 22:46

Jay Sudo's user avatar

Jay SudoJay Sudo

991 silver badge2 bronze badges

2

I understand you have a scenario with ErrorDocument already defined within your apache conf or .htaccess and want to make those pages appear when manually sending a 4xx status code via php.

Unfortunately this is not possible with common methods because php sends header directly to user’s browser (not to Apache web server) whereas ErrorDocument is a display handler for http status generated from Apache.

answered Nov 27, 2014 at 15:22

labemi's user avatar

Refresh the page after sending the 403:

<?php 
header('HTTP/1.0 403 Forbidden');
?>
<html><head>
<meta http-equiv="refresh" content="0;URL=http://my.error.page">
</head><body></body></html>

answered Oct 12, 2014 at 6:08

Richard's user avatar

1

Web designers have gotten used to turning errors into opportunities. It’s no secret that the common, most widely occurring (and surprisingly recognizable) HTTP status code 404, aka “Not Found,” was forced by developers to bring benefits to the project. In the past it scared away users, destroyed the overall impression and was a nightmare for developers. Everyone wanted it to disappear once and for all.

Today, it is an essential detail of a website. WordPress even has a specifically assigned template for it. The “404 page” is an integral element of user experience. In the majority of cases, it has not only a beautiful design but also a theme that is aimed to contribute to the entire aesthetic of a website.

Along with the well-thought-out design, interactions and even animations, it includes useful links and getaways that help lost users to get back on track. However, the “404” error in web design is like Hipsters in real-world: They still catch our eye with their dorky glasses, “vintage” shirts and beards but they are nothing new to us. As for the “403” error, that’s a different story. It’s not as popular as its next of kin, but still, it occurs and not once in a blue moon.

Just for background, HTTP status code 403, aka “403 Forbidden”, means that you do not have permission to access the page. Reasons can vary, starting with inappropriate folder permissions and ending with a banal requirement of login credentials. Nevertheless, the rule of thumb dictates that any error is an opportunity to effect improvements. So why not turn the dummy “403 page” into a place that will serve the same duty as the “404 page”?

Let’s consider a dozen splendid takes on this type of error. They not only serve as a source of inspiration but also a source of ready-to-use solutions.

You Shall Not Pass

“You shall not pass” – was said once by one of the most powerful white-bearded wizards in the fictional world (I hope all the fans of Dumbledore forgive me for this). The final phrase of Gandalf the Grey (note Grey, not White) perfectly fits into the context here. And Noah Rodenbeek, A van Hagen and Jhey show this in practice. Their code snippets are impregnated with a spirit and charm of “The Hobbit” novel. While the first two artists re-created Gandalf with his staff, the latter just hinted at the scene, yet quite successfully.

HODOR 403

If the motifs from fictional novels featured above are not enough for you, then you should set your eyes on this code snippet from Yasio. Surprise-surprise, he got his inspiration from George R. R. Martin’s series of fantasy novels. He has come up with a work called HODOR 403. I believe for the majority out there this solution is self-explanatory. For the rest, I recommend switching to HBO and seeing for yourself why this fictional character goes perfectly well with this type of an error.

Use of Illustration and Animation

Other solutions in our list were guided by the notion that “403” symbolizes a forbidden area so that animated and static CSS illustrations were recreated namely with this idea in mind.

Error 403 – Forbidden by Aimie depicts a classic scene from the fairy tale. The animated bats, witch’s house, bare trees and creepy typography that are featured in the hours of darkness certainly do the trick here.

403 Forbidden by Dylan and 403 Forbidden by Visual Composer have some unique medieval allure. “Close the Gates”: The projects evoke namely these associations. The first one features the classic wooden guard gate door that closes before your very eyes; the second one also goes for a guard gate topic and depicts a mechanism with cogs and chains that reveals the forbidden sign.

Arturo Wibawa’s vision of the forbidden area is presented via marvelous, highly-detailed and even partially animated CSS illustration of the famous Chinese ‘The Purple Forbidden City,’ aka Palace Museum nowadays.

It’s Watching You

403 Forbidden Page by Mariana is marked by a whimsical monster-like character that, thanks to direction-aware effect, follows your mouse cursor everywhere. It recreates a feeling of being watched all the time. It also imitates a fancy fairy guard that does not allow moving forward. The project feels fun in spite of the “menacing” look of the mascot.

Be Persistent

Gabriele Corti also offers a vision of a “403” error page. His “Persistence is a key” project depicts an entire process of initially denying access and granting it after the right user action. The right actions imply inserting a key into a keyhole Nevertheless, you can always use this concept as a base for some advanced actions like inputting login and password.

Keeping it Simple

403 by lsgrrd is an oversimplified take on a “403 Page” that certainly has a right to exist. It is minimal but straight to the point. It has a certain digital quality that oozes techno vibe inherent to the computer sphere. The blinking cursor at the end in tandem with the digital typography produces a fantastic effect. The solution is clean, elegant and straightforward.

Are You on the List?

We are going to end our collection with the project made by Cassidy Williams. Unlike the majority featured here, this solution is a metaphor from the real world that illustrates the typical situation in any popular nightclub. The bouncer is the heart and soul of this code snippet. The character was even partially animated to make everything look lifelike.

Another Opportunity to Engage Users

Truth be told, “403 Error” is not as widespread as “404 Error”, nor is it as popular and recognizable. Nevertheless, it still exists and occurs time after time. That creates a hole in a website that can break the entire user experience. So, seize the opportunity and turn it into a valid part of the project. It will undoubtedly win over some new visitors and will prevent you from losing the old ones.

Related Posts

  • 8 CSS Snippets for Creative Hyperlink Hover Effects
  • 8 CSS & JavaScript Snippets for Creating Paginated Navigations
  • 8 CSS & JavaScript Snippets for Building Mega Menus
  • 8 CSS & JavaScript Snippets for Creating eCommerce Microinteractions
  • 8 CSS & JS Snippets for Creating Pixelated Backgrounds
  • 10 CSS, JavaScript & SVG Snippets for Creating Logos
  • A Long Time Ago: Code Snippets Inspired by Star Wars
  • 10 CSS & JavaScript Snippets for Creating Interactive Skeuomorphic UIs
  • 8 CSS & JavaScript Snippets for Creating Interactive Timelines
  • 8 CSS & JavaScript Snippets for Creating Unique Social Media Icons

This page may contain affiliate links. At no extra cost to you, we may earn a commission from any purchase via the links on our site. You can read our Disclosure Policy at any time.

This post about creating a 403 error page template is kind of a follow on from my recent post about how to disable directory listing in WordPress. In that guide I talk about locking down the potential security risk of leaving your directories visible. The result of following the guide means that your directory listings will be hidden and replaced by a 403 error.

The 403 error is an HTTP status code that occurs when you try to access a URL the hosting server does not allow. The server effectively acknowledges the URL exists, but doesn’t permit you to see it. In terms of disabling directory listings this is great. However, it’s perhaps not the most slick experience for anyone who accidentally hits a 403 error on your domain.

For example, a common default 403 error page often looks like this:

Standard 403 Error

It doesn’t explain what has happened and neither does it give you a route back to your WordPress blog.

What follows then is a super-simple way to create a basic custom 403 error page template for your WordPress blog, so you can give visitors instead a little more detail about what to do next.

A Note on Your Host & 403 Errors

It may be that your hosting provider has configured a 403 error page out of the box. For example, I use SiteGround and the default 403 error page for me is this:

SideGains 403 Error Page Before Template

It provides basic information but no link back to my blog. My 403 template will also be basic, but you’ll be able to edit it as you’d like with your own HTML and CSS.

For me personally I am happy to have a basic page since most people trying to access a page that leads to a 403 error are probably not your average site visitor (i.e. they might be probing your site for a vulnerability).

I mentioned this is very simple… and it is: there are only two steps! However, you will need to be comfortable working in the control panel of your hosting server. SideGains is hosted on a SiteGround server and so I use cPanel for this example. You might use something else such as DirectAdmin or Plesk… it depends on who your host is. However, the steps should be very similar.

Step 1 – Creating Your 403 Template

The first step is to create a new error template file in which we’ll add the 403 message.

Click the File Manager tool in your cPanel dashboard to view all the files in your home directory.

cPanel File Manager

Note: Your file manager may have a different name in DirectAdmin or Plesk.

You are now looking at the files on your server. Make sure you are in the home directory of your WordPress installation. If you’re unsure which is your home directory, you should see the WordPress directories wp-admin, wp-content, wp-uploads etc. For most people it will be /public_html.

We are going to create your 403 error page template so click on the new file icon to create your template file:

cPanel File Manager Create File

You’ll get a pop-up dialogue box in which you’ll input the name of the file you’re making. Call this file error.php as in the below image:

cPanel Create New File

You should now see your error.php file in your File Manager listings. Right click on it and select “Edit” or “Code Edit” (they both do the same thing, but one of them gives you line numbers).

When the file editor opens you’ll see a blank page. You’re going to copy and paste the following code into your error.php file.

The 403 Error Page Code

<?php
$page_redirected_from = $_SERVER['REQUEST_URI'];
$server_url = "https://" . $_SERVER["SERVER_NAME"] . "/";
$redirect_url = $_SERVER["REDIRECT_URL"];
$redirect_url_array = parse_url($redirect_url);
$end_of_path = strrchr($redirect_url_array["path"], "/");
switch(getenv("REDIRECT_STATUS"))
{
	# "400 - Bad Request"
	case 400:
	$error_code = "400 - Bad Request";
	$explanation = "The syntax of the URL submitted by your browser could not be understood. Please verify the address and try again.";
	$redirect_to = "";
	break;
	# "401 - Unauthorized"
	case 401:
	$error_code = "401 - Unauthorized";
	$explanation = "This area requires a password or is otherwise protected. If you feel you have reached this page in error, please return to the homepage and try again, or contact the webmaster if you continue to have problems.";
	$redirect_to = "";
	break;
	# "403 - Forbidden"
	case 403:
	$error_code = "403 - Forbidden";
	$explanation = "This area requires a password or is otherwise protected. If you feel you have reached this page in error, please return to the homepage and try again, or contact the webmaster if you continue to have problems.";
	$redirect_to = "";
	break;
}
?>
<!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">
<head>
	<link rel="Shortcut Icon" href="/favicon.ico" type="image/x-icon" />
<?php
	if ($redirect_to != "")
	{
?>
	<meta http-equiv="Refresh" content="5; url='<?php print($redirect_to); ?>'">
<?php
	}
?>
	<title>Page not found: <?php print ($redirect_to); ?></title>
</head>
<body>
<h1>Error Code <?php print ($error_code); ?></h1>
<p>The page you requested was not found. <?PHP echo($explanation); ?></p>

<p>You may want to try starting from the home page: <a href="<?php print ($server_url); ?>"><?php print ($server_url); ?></a></p>
<hr />
<p><i>A project of <a href="<?php print ($server_url); ?>"><?php print ($server_url); ?></a>.</i></p>
</body>
</html>

Click the “Save” button and then click “Close” and you’ll have just created the 403 error page template. Incidentally I’ve also added rules for 400 (Bad Request) and 401 (Unauthorized) into this to present messages for these errors too.

Now we have to instruct your server to refer these errors to your error.php page.

Step 2 – Editing Your .htaccess File for a 403 Redirect

If you haven’t come across .htaccess is, or don’t know where to look for it on your server, I’ve posted about it here: Can’t Find Your .htaccess File? Here’s What to Do.

The .htaccess file is a configuration file that instructs a server how to handle certain requests. We’re going to use it in this case to tell it how to handle a 403 error.

You can find .htaccess in your home directory using the cPanel File Manager. This is the directory where you installed WordPress… for most people it will be /public_html.

Because .htaccess is a “hidden” file you may not see it. If you can’t see it in your home directory, visit my “Can’t Find Your .htaccess File?” post for instructions on how to make it visible.

When you’ve located your .htaccess file, the first thing you’re going to do is make a back up copy. .htaccess is a VERY important file and if it somehow gets broken when you edit it, you’re going to need to be able to swap it with your back up copy.

So… when you’ve located .htaccess, right click on it and make a duplicate (call it something like BKUP.htaccess_BKUP so you know what it is). If you get into any trouble you can simply delete your corrupt .htacces and make a duplicate copy of your BKUP.htaccess_BKUP, but call it .htaccess to replace the one you deleted.

Once you have your back up copy, you can safely edit your .htaccess file. So right click on it and select either the “Edit” or “Code Edit” option.

You’re going to add 3 lines to .htaccess beneath the last entry in the file. These lines are:

ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php

This tells your server to forward requests for 400, 401 and 403 errors to your error page template.

Be sure to leave a blank line at the end of the file (this is important) and click “Save”. When the file is saved, close the window.

Checking Your 403 Error Page Template is Working

The next step is to check that everything is working as it should be. You can do this simply by trying to visit your wp-content/uploads directory. For me I would visit:

https://www.sidegains.com/wp-content/uploads/

And this is the 403 error page template realized in a browser:

Live 403 Error Template

That’s it! You can of course modify error.php to customize it further, but this basic message is sufficient to give a brief explanation of why this page says what it says and provide people with a way back to your homepage.

Template 403 Error Page in WordPress

Please leave me a comment below if you’ve implemented this or if you need further information about setting up a 403 error page template for your WordPress blog.

Возможно, вам также будет интересно:

  • Своя ошибка 404 для joomla
  • Своя игра ошибка установки 0x80070490
  • Своя игра ошибка игрового движка
  • Своя игра ошибка загрузки медиа
  • Своя игра отправка пакета на сервер неизвестная ошибка

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии