Introduction
You’ve probably seen the standard Apache 404 error page many times, when you’ve visited a Web page that no longer exists:
Not very pretty, is it? It doesn’t help much either. Something like the following would be much more useful:
The second error page looks better, is more friendly, and gives the visitor some more options to try (as opposed to just going to another website!).
In this tutorial we’ll show you how to set up your website to serve your own error page rather than the default Apache one.
Apache’s ErrorDocument directive
It’s really pretty easy to get Apache to serve up a custom error page. It’s all controlled through Apache’s ErrorDocument
directive. This is a simple one-liner that tells Apache what to do when a particular HTTP error is triggered:
ErrorDocument error-code document
error-code
is the HTTP error code. Here are some common error codes that you might like to create custom pages for:
Code | Error | What It Means |
---|---|---|
404 | Not Found | The page or file couldn’t be found on the site |
401 | Unauthorized | The page or file can’t be viewed without the correct username/password (see our Password protecting your pages with htaccess tutorial) |
403 | Forbidden | The page or file is not allowed to be viewed at all |
500 | Internal Server Error | Something on the server broke (often a CGI script) |
document
is the custom page or message that you’d like Apache to serve up instead. So if for example we’d created a nice pretty 404 page called nice404.html
, stored in the root folder of our website, then we could get Apache to serve it as follows:
ErrorDocument 404 /nice404.html
We could also create a nice page for a 500 error (perhaps asking the visitor to contact us so we can look into the problem). We might call it nice500.html
and put it in the root folder, and add another ErrorDocument directive as follows:
ErrorDocument 500 /nice500.html
You get the idea.
Use relative URLs
Note that it’s best to use an error document on your own site, and reference it with a relative URL as we’ve done above. For example, although you could put your error document on another site and then reference it with an absolute URL:
ErrorDocument 404 http://www.example.com/nice404.html
it will cause Apache to issue a redirect to the browser rather than a hard 404 error. This is generally a bad thing, because Web robots (e.g. search engine spiders) won’t be able to find broken links easily. So it’s not recommended.
Custom error messages
If you don’t have time to design a nice pretty custom error page (or you simply can’t be bothered!), you can at least get Apache to display a slightly more friendly error message. Simply put the message after the error code instead of the error page URL:
ErrorDocument 403 "You really shouldn't be looking at that, you naughty thing!"
(Note that for the older Apache 1.3 server you should miss off the last double quote.)
Creating the .htaccess
file
So where do you put the ErrorDocument
directive? Usually you put it in your Web server’s config file, or in a .htaccess
file in your website root. As you probably won’t have access to your Web server’s config (unless you’re the server administrator), we’ll describe the .htaccess
method.
Open your favourite text editor on your PC, and create a new file. Save the file with the name .htaccess
(note the period (.
) at the start of the file name).
Now add your ErrorDocument
lines to your .htaccess
file – for example:
ErrorDocument 404 /nice404.html
ErrorDocument 500 /nice500.html
Then save the file and upload it to your website, placing it in the root (top level) folder of your website. Don’t forget to upload your custom error page(s) too!
Testing the custom error page
The last thing to do is test your custom error page or pages. For example, to test a custom 404 page, visit a URL on your site that you know doesn’t exist:
http://www.example.com/abcdef.html
If all goes well you should see your nice friendly error page appear!
If it doesn’t work, check that you’ve uploaded both your custom error page and your .htaccess
file to your website, and that the contents of the .htaccess
file is correct. You can test that you’ve uploaded your error page to the right place by entering its URL in your browser – for example:
http://www.example.com/nice404.html
(If you don’t see your nice error page then you probably haven’t uploaded it correctly.)
Also check that your Web server supports .htaccess custom error documents (it needs to be an Apache server, and your server admin needs to have enabled the FileInfo
override for your site).
An Internet Explorer gotcha
Internet Explorer (bless it) will often ignore your carefully crafted pretty error page completely, and instead display its own “friendly” message. To prevent this happening, make sure that the size of your error page file is at least 512 bytes (add some filler text in HTML comments if you have to). IE will now display your error page rather than its own.
Further info
For full information on Apache’s ErrorDocument
directive, see the Apache Core Features documentation.
To include a block of code in your comment, surround it with <pre> ... </pre>
tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code>
tags.
Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre>
.
12 июля, 2015 12:38 пп
6 351 views
| Комментариев нет
Cloud Server, Ubuntu, VPS
Apache – самый популярный в мире веб-сервер; многофункциональный и гибкий, он постоянно поддерживается командой специалистов.
При проектировании веб-страниц часто возникает необходимость настроить каждую из них в индивидуальном порядке. Это касается и страниц ошибок, которые появляются в случае, если запрашиваемый контент по какой-либо причине недоступен. В этом руководстве показано, как настроить Apache для отображения пользовательских страниц ошибок в системе Ubuntu 14.04.
Требования
Для выполнения данного руководства нужен пользователь с привилегиями sudo. Чтобы настроить такую учётную запись пользователя, обратитесь к этому руководству. Кроме того, нужно предварительно установить Apache; подробные инструкции по установке можно найти здесь.
Создание пользовательской страницы ошибок
Сначала нужно создать пользовательские страницы ошибок.
Примечание: Для тестирования можно использовать следующий код без изменений. Чтобы создать свою страницу ошибок, просто замените текст в echo в приведённом ниже коде.
Страницы ошибок будут храниться в каталоге /var/www/html – стандартном каталоге document root веб-сервера Apache. Для примера создайте страницу ошибки 404 (по имени custom_404.html) и общую страницу для ошибок 500 (custom_50x.html).
echo "<h1 style='color:red'>Error 404: Not found :-(</h1>" | sudo tee /var/www/html/custom_404.html
echo "<p>I have no idea where that file is, sorry. Are you sure you typed in the correct URL?</p>" | sudo tee -a /var/www/html/custom_404.html
echo "<h1>Oops! Something went wrong...</h1>" | sudo tee /var/www/html/custom_50x.html
echo "<p>We seem to be having some technical difficulties. Hang tight.</p>" | sudo tee -a /var/www/html/custom_50x.html
Итак, теперь на сервере есть две страницы ошибок.
Настройка Apache для отображения пользовательских страниц ошибок
Теперь нужно настроить Apache для поддержки только что созданных страниц в случае возникновения соответствующей ошибки. В каталоге /etc/apache2/sites-enabled откройте файл виртуального хоста. В руководстве используется стандартный файл хоста 000-default.conf, но вы можете работать с пользовательскими хостами.
sudo nano /etc/apache2/sites-enabled/000-default.conf
Направьте Apache на соответствующие страницы ошибок.
Для того чтобы связать каждый тип ошибки со специальной страницей, используйте директиву ErrorDocument. Это можно сделать в файле хоста. В целом, нужно просто указать код состояния HTTP для каждой страницы, и тогда страница появится на экране в случае возникновения указанной ошибки.
В данном случае настройки будут выглядеть так:
/etc/apache2/sites-enabled/000-default.conf
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
ErrorDocument 404 /custom_404.html
ErrorDocument 500 /custom_50x.html
ErrorDocument 502 /custom_50x.html
ErrorDocument 503 /custom_50x.html
ErrorDocument 504 /custom_50x.html
</VirtualHost>
Этого кода достаточно для настройки обслуживания страниц ошибок.
Однако рекомендуется добавить ещё один блок конфигураций, чтобы клиенты не могли запрашивать страницы ошибок напрямую. Это предотвратит путаницу (например, запрошенная напрямую страница ошибки будет сообщать пользователю об ошибке, даже если код состояния – 200 (Success)).
Чтобы настроить такое поведение веб-сервера, нужно добавить блок Files для каждой пользовательской страницы ошибок. Также нужно проверить, установлена ли переменная окружения REDIRECT_STATUS; она должна быть установлена, только если директива ErrorDocument обрабатывает запрос. Если переменная окружения пуста, сервер будет обслуживать страницу 404:
/etc/apache2/sites-enabled/000-default.conf
<VirtualHost *:80>
. . .
ErrorDocument 404 /custom_404.html
ErrorDocument 500 /custom_50x.html
ErrorDocument 502 /custom_50x.html
ErrorDocument 503 /custom_50x.html
ErrorDocument 504 /custom_50x.html
<Files "custom_404.html">
<If "-z %{ENV:REDIRECT_STATUS}">
RedirectMatch 404 ^/custom_404.html$
</If>
</Files>
<Files "custom_50x.html">
<If "-z %{ENV:REDIRECT_STATUS}">
RedirectMatch 404 ^/custom_50x.html$
</If>
</Files>
</VirtualHost>
Когда страницы ошибок запрашиваются клиентами, возникает ошибка 404, потому что переменная среды не установлена.
Тестирование страницы ошибок 500
Проверить работу страницы ошибок 404 очень просто: достаточно запросить любой несуществующий контент. Но чтобы протестировать страниц ошибок 500, нужно создать фиктивную директиву ProxyPass.
Добавьте директиву ProxyPass в конец конфигурационного файла. Отправьте запросы для /proxytest на порт 9000 на локальной машине (на этом порте не запущено ни одного сервиса):
/etc/apache2/sites-enabled/000-default.conf
<VirtualHost *:80>
. . .
ErrorDocument 404 /custom_404.html
ErrorDocument 500 /custom_50x.html
ErrorDocument 502 /custom_50x.html
ErrorDocument 503 /custom_50x.html
ErrorDocument 504 /custom_50x.html
<Files "custom_404.html">
<If "-z %{ENV:REDIRECT_STATUS}">
RedirectMatch 404 ^/custom_404.html$
</If>
</Files>
<Files "custom_50x.html">
<If "-z %{ENV:REDIRECT_STATUS}">
RedirectMatch 404 ^/custom_50x.html$
</If>
</Files>
ProxyPass /proxytest "http://localhost:9000"
</VirtualHost>
Сохраните и закройте файл.
Затем включите модули mod_proxy и mod_proxy_http:
sudo a2enmod proxy
sudo a2enmod proxy_http
Тестирование страниц ошибок
Проверьте конфигурационный файл на наличие ошибок:
sudo apache2ctl configtest
Если команда обнаружила любые ошибки, исправьте их. Затем перезапустите Apache:
sudo service apache2 restart
Теперь откройте домен или IP-адрес сервера и запросите несуществующий контент, чтобы проверить работу страницы 404:
http://server_domain_or_IP/thiswillerror
На экране должна появиться страница 404:
Error 404: Not found :-(
I have no idea where that file is, sorry. Are you sure you typed in the correct URL?
Откройте фиктивный proxypass, чтобы проверить работу страницы 500 (на экране должен появиться код состояния 503 service unavailable):
http://server_domain_or_IP/proxytest
Если всё было выполнено верно, на экране появится:
Oops! Something went wrong...
We seem to be having some technical difficulties. Hang tight.
После тестирования удалите фиктивную директиву из конфигураций Apache. Также нужно отключить модули proxy:
sudo a2dismod proxy
sudo a2dismod proxy_http
В завершение перезапустите веб-сервер:
sudo service apache2 restart
Заключение
Итак, теперь на сайте есть уникальные страницы ошибок. Пользовательские страницы ошибок – это отличный способ помочь посетителям понять, в чём дело, предоставить им всю необходимую информацию об ошибке и полезные ссылки (не забудьте убедиться, что ссылки работают даже в случае возникновения ошибок).
Tags: Apache, Ubuntu 14.04
Web Designing can be fun and interesting. Using the current cutting edge of web programming courtesy HTML5, CSS3 and jquery a beginner can easily create mind blowing web templates that look cool and refreshing. But all the hours of work to decorate the face of your site is wasted if the user encounters a bland looking error page containing technical jargon that leaves visitors scratching their heads. So custom error pages are the order of the day!!!
Advantages of custom error pages
- You can create an error page using the template you used to create your website. Thus even when someone encounters an error he/she will feel at home (or at your site)
- Custom error pages boost your search engine ranking.
- Since the error page is at your control you can write stuff that tells the user in plain English what caused the error.
So lets take a look on creating custom error pages on the mostly widely used open source web server software Apache HTTP server.
Step 1: Design the error page
I say design instead of create because you should use the same theme/template which the website uses for the error. The next man thing is that it should contain both technical and non technical information about the error. For example if you’re designing a “404 page not found” error page tell the user all the possibilities of arriving at this error. It could be due to an outdated link or a misspelt word or using a different case (lowercase or uppercase) for the web page name.
Use the php code $_SERVER[‘REQUEST_URI’] to display the name of the non existing page/directory. Include a search box and tell users to search for what they were looking for. Tell them to also take a look at your Sitemap. Save the file as 404.html or any name that best describes the error. Pages can be created for the following common error codes
Error Code | Reason |
---|---|
401 | Authentication Required This error occurs if you are prompted to enter a valid username and password to view a page and you press cancel i.e. if you try to view a htpasswd or htdigest protected directory/file |
403 | Forbidden This error occurs if you try to view a file/directory that doesn’t have permissions to be viewed to the world. This includes htaccess, htpasswd files and directories forbidden from listing out their contents |
404 | Page Not Found If a non existing file or directory is requested this error is displayed |
500 | Internal Server Error Occurs when wrong syntax is used in htaccess file |
Step 2: Edit the .htaccess file
Now that you’ve created the error page you should tell the web server to display it whenever an error is encountered instead of displaying its own default. So you need to create/edit your htaccess file. Search for it inside the public_html or www or htdocs folder. Don’t fret if it isn’t there just create a file named .htaccess (the dot at the beginning of the file is very important) Add the following line to that file.
ErrorDocument [error code] /[path to error page]
Example:-
ErrorDocument 404 /errors/404.html
Don’t forget to save the htaccess file.
Step 3: Testing the error page
Now for the fun part starts. Type your website’s url followed by some rubbish e.g. https://websistent.com/something Now if you’ve done everything correctly you should see your custom 404 error page. If you get a 500 Internal server error check for any syntax errors in the .htaccess file. If you see the error page file name, then its because you’ve omitted the slash in front of the file name path.
Bad practices for custom error pages
I’ve come across some websites which use their home page as an error page. Now this might seem simpler but just imagine the plight of a newbie who clicks an outdated link on that website and lands up on the home page. Such a person would be clueless on what has happened. Another bad practice is to show the website’s Sitemap.
Did you know that Apache web server allows you to configure custom 404 error page for your website? Using ErrorDocument directive you can easily configure custom error page in Apache, without any coding. In this article, we will look at how to create custom 404 page in Apache. You can also use these steps to configure custom error pages for other error codes such as 403, 500, 502, etc.
Here are the steps to configure custom 404 error page for your website. We will use the ErrorDocument directive to setup custom 404 page. Please make sure that you have your error page file ready, before you proceed further. We have assumed that our error file error404.html is located at website root folder /var/www/html/.
You can add ErrorDocument directive in .htaccess file, virtual host configuration file or your main server configuration file, as per your requirement.
1. Open .htaccess file
You will typically find .htaccess file in your site’s root folder (e.g /var/www/html/). You can open it using vi editor
$ sudo vim /var/www/html/.htaccess
If you have not setup .htaccess but have setup virtual hosts, then you can also open your virtual host configuration file (e.g /etc/apache2/sites-enabled/example.com for your domain example.com)
$ sudo vim /etc/apache2/sites-enabled/example.com
Alternatively, you can also open the default virtual host configuration file
$ sudo vim /etc/apache2/sites-enabled/000-default.com
Also read : How to Create Self-Signed Certificate for Apache
2. Configure 404 Error Page
Add the following line to .htaccess file
ErrorDocument 404 /error404.html
In the above line, we specify the error response code 404 and the custom page error404.html to be served for it. You can also configure error pages for other response codes such as 500, 502, 403, etc.
If you are using Virtual host file, add the above line inside VirtualHost tag
<VirtualHost> ... ErrorDocument 404 /error404.html ... </VirtualHost>
Also read : How to Use Apache bench for Load Testing
3. Create 404 Error page
Create custom error file error404.html using text editor, or a page builder like Squarespace, WordPress, or Wix.
4. Restart Apache Server
Restart Apache Server to apply changes
$ sudo service apache2 restart
Hopefully, this article will help you create custom 404 pages for your website. You can use these steps to configure custom pages for other error codes such as 500, 502, 403, etc.
Ubiq makes it easy to visualize data, and monitor them in real-time dashboards. Try Ubiq for free.
Related posts:
- About Author
Steps to configure apache2 to use custom Error pages on Ubuntu
Creating your custom error page
Now let’s dive in adding a custom error page to your site.
Sample Code
<!DOCTYPE html>
<html>
<body>
<h1>404</h1>
<a href=»index.html” class=”err-btn”><i class=”fas fa-angle-right”></i></a>
</div>
</body>
</html>
You can also make your own version of 404 html page more visually appealing
Implement the 404 page
Now that you have your custom error page coded (referred to as 404.html from here on), Now quickly go to the home directory /var/www/html/.
The next step is editing your Apache localized-error-pages file to use 404.html instead of the default error page.
Locate your localized-error-pages configuration file in the/var/www/html/.directory. The file will be called localized-error-pages.conf
Now you can see there are different types of error pages that can be overridden. Just uncomment line 8 that starts with “ErrorDocument 404” and add “/404.html” instead of the default location for that error page. You can simply repeat this or create different custom error pages for each type of error.
Save and Exit Once Done
ErrorDocument 404 /404.html
Now the last step is to restart your Apache server in order for the changes to take effect
sudo service apache2 restart