Ошибка 404 апач

12 июля, 2015 12:38 пп
6 519 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

A 404 File Not Found page — also known as a 404 error page — is a web page that lets a user know when the page they are trying to access cannot be located. A custom 404 error page is a 404 error page that is crafted thoughtfully with user experience in mind. Custom 404 error pages are put into place to fend off confusion, explain the situation, and offer thoughtful next steps that keep the ball rolling.

To get a custom 404 error page up and running on your website, you’ll need to do some communicating with your server.

404-error_PaulYokota

An example of a custom 404 error page.

How you go about getting a custom 404 error page setup on your server will vary greatly depending on your server type. This article addresses how to set up a custom 404 error page on an Apache server.  

Getting a custom 404 error page up and running on the Apache Server is a five-part process:

  1. Design an on-brand custom 404 error page.
  2. Publish your custom 404 error page.
  3. Determine what type of server you are using, or if you are using a CMS like WordPress.
  4. Use your public_html folder and .htaccess file to tell your server to deliver the 404 error page anytime a request is made for a web page that doesn’t exist.
  5. Test it! Make sure your 404 error page is live and working as expected.

In this post we cover parts 3, 4 and 5 of this process; you should already have parts 1 and 2 done. If you haven’t designed your custom 404 error page yet, read How to Design a 404 Error Page That Saves a Sale for strategic inspiration.

How to Determine Your Server Type

Your website is hosted on a server that dishes out web pages when people navigate to URLs within your domain. There are several types of servers.

server-illustration-Apache_2First, the easiest one: If you are using WordPress, then you know you’re using WordPress and you should read about WordPress 404 error page setup; this Apache server article will not help you. Similarly, if you happen to be using Microsoft IIS, then you should read our How to Configure a Custom 404 Error Page in Microsoft IIS Server post.

If you aren’t using WordPress and you don’t know what kind of server you are using, call your server provider (the people you pay to host your website every month – like BlueHost, for instance), and ask them. While you have them on the line, make sure to also ask them if it is possible to set up a custom 404 error page; most server providers allow you to do this, but not all.

If your server provider tells you your website is hosted on the most widely used Web server — the Apache server — then read on!

Proceed with Caution!

If you are reading this blog post, I am assuming that you don’t have the luxury of asking an IT department to set your custom 404 error page up for you. If you do have an IT/systems department to refer to, by all means, ask for help! IT folks love servers and lines of code that talk to servers, and they effectively know how to handle both.

If you’re going in on your own, it’s smart to make sure you have your entire website backed up before you make any changes to code at the server level. The amendments we’ll be making to add a custom 404 error page are minimal, but it’s always better to be safe than sorry when it comes to tinkering with server-side code.

How to Tell Your Server to Deliver the 404 Error Page

This blog post is written to help folks using the Apache server add a custom 404 error page to their website. Like most processes, there’s inherently server-illustration-3more than one way to do this. The following five-step process is the most universal method, as it only requires FTP access to your server and a text editor, like Notepad++ (on a PC) or TextEdit (on a Mac). (It’s worth mentioning here that Notepad [the default text editor in Windows] and Notepad++ are not the same thing. If you’re using a PC, we recommend downloading the free Notepad++ text editor; using the standard release version of Notepad may cause errors if the server is running Linux.)

Step 1: Locate or create your .htaccess file

After identifying that you are using the Apache server, the first step is to locate your .htaccess file.

A .htaccess file is a file that communicates how and when your server should deliver specific information to your end user. In this case, specifically, when your server should deliver a fancy, custom-made 404 error page. Your .htaccess file should already be in the root directory of your website.

To access your .htaccess file:

  • Connect to your server using an FTP editor like CyberDuck or Filezilla.
  • Find the folder that contains your public website files. Public_html is a common name for this folder. While your folder may or may not be named public_html, we will refer to this folder as the public_html folder throughout the rest of this tutorial.
  • Locate the .htaccess file inside the public_html folder.

If you see a .htaccess file, move on to step three.

cyberduck-publichtml-htaccess_private2

Use your FTP client to locate your .htaccess file. It should be in the folder where you keep all your public website files.

If you don’t see a .htaccess file, make sure that your FTP is set to show hidden files (notice that period in front of the .htaccess file? That period means your .htaccess file it is a hidden file.). To show hidden files using Cyberduck, go to the View dropdown, then choose Show Hidden Files. To show hidden files using Filezilla, go to the Server dropdown, then choose Force Showing Hidden Files.

Cyberduck-show-hidden-files

Show hidden files in Cyberduck using the View dropdown menu, as seen here.

If you force your FTP to show hidden files and you still don’t see a .htaccess file, it means you don’t have one and you will have to make one. In that case, move on to step two.

Step 2: Create your .htaccess file (if you don’t already have one)

Fair warning: While any novice can create a .htaccess file (we’re going to show you how right here!), if you have an IT department this is a really, really good time to bring them in the loop. If you don’t have an IT department, now would be a great time to create that website backup if you haven’t already!  Your .htaccess file is going to communicate critical information to every page of your website, so it’s smart to have a backup plan in case things get a little haywire.

To create an .htaccess file, use a text editor like Notepad++ on a PC, or TextEdit on a Mac. Name the file .htaccess — and don’t forget the “.” It needs to be named .htaccess (periodhtaccess), not just htaccess. To keep your .htaccess file clean, make sure your text editor has word wrap disabled, and that it is using UNIX-style line endings. Also, make sure there aren’t any file extensions added to your .htaccess file when you save it. You want to choose All Files (not Text or any other file type) from the Save As Type dropdown menu and save to the Desktop.

Save-htaccess-file-as-ALL-TYPES_2

That’s it! After you save you’re done creating your .htaccess file. The file won’t do anything until you’ve uploaded it to the public_html folder of your server via FTP but, to streamline the process, we’ll wait until after we amend the file (as outlined in step three) to upload it to the server.

Step 3: Use a text editor to edit the .htaccess file

Using your text editor, add this one line of code to your .htaccess file, followed by a blank line:

ErrorDocument 404 /custom-404.html

There’s four parts to this line of code: [the phrase ErrorDocument] [the error number] [the absolute URL of the web page where custom 404 content lives] [the blank line that follows the line of code]. Make sure you carefully include all four elements (No typos! No exclusions!) and make sure you replace the placeholder “custom-404.html” with the actual URL extension where your custom 404 error page lives.

The URL that you put in the ErrorDocument directive needs to be a:

1. Relative URL — no http and no domain name.

2. Static file — meaning Apache can serve it directly (no proxy, no application server, etc.); otherwise, Apache will assume the file is on another server and issue a redirect to the browser to go there.

It’s this one line of code that tells your .htaccess file to deliver a custom 404 page when someone asks for a web page that cannot be located.

Step 4: Use FTP to upload your amended .htaccess file to your server

Make your .htaccess file alliiivvvveeee (like Frankenstein) by using your FTP to upload your amended file to your server.

Once it’s uploaded to the root directory of your server, it’s live and your 404 error page should be working (assuming you’ve made your 404 error URL live, as well).

Step 5: Test it! Make sure your 404 error page is working

The final step in every optimization process needs to be testing. We never set it and forget it in our industry. To test if everything is in working order testtubeswith your .htaccess file and your new custom 404 error page, use your web browser to navigate to a page on your website that you know doesn’t exist. For example: www.YourWebsite.com/chelsea-is-awesome.

If you see your custom 404 error page, everything is working! You have succeeded!

If you don’t see your custom 404 error page, something is wrong. Try to isolate the problem with these troubleshooting tips:

  • Do all the other pages on your website work? If yes, that means the problem has to be with your 404 error page URL or your .htaccess file. If no, you have created a bigger issue and may want to revert back to a backup version of your .htaccess file.
  • Can you spot any typos in your ErrorDocument line of code?
  • Did you add a blank line after your ErrorDocument line of code?
  • Did you disable word wrap when you created your .htaccess file? Is your ErrorDocument code on one single line? If you are using Windows, is the document using UNIX-style line endings?
  • Is your .htaccess file saved as .htaccess.txt? It shouldn’t be. It should just be .htaccess with no file extension. (The trick is to choose All Files from the Save as Type dropdown when you save the file in your text editor; make sure no extra file extensions get added on.)
  • If you navigate directly to your 404 error page using the absolute URL, does it work?

If none of these troubleshooting tips uncover your problem… now might be a good time to seriously consider hiring that contract IT guy or gal.

You Can Do This!

Even if you are a UX minimalist — no matter how big or small your company is — you need to consider a properly configured 404 error page a technical SEO essential. You absolutely can do all the steps outlined in this post, from locating your hidden .htaccess file or creating a new one, to writing a line of code that works. Think of it like baking a cake: you have the recipe, now you just need to put all the ingredients together.

Just follow this five-step process:

1. Get confirmation that you’re using the Apache server and the thumbs up to proceed with a custom 404 from your server host.

2. Work with your web designer to create a custom 404 error page.

3. Make your 404 error page live.

4. Use your public_html folder and .htaccess file to tell your server to deliver the 404 error page anytime a request is made for a web page that doesn’t exist.

5. Test, test, test.

Have questions? Ask in the comments section below.

Next Steps_600x203

Learn more about servers and how to get your web pages found, crawled and indexed with these technical SEO tips.

Chelsea Adams Brooks is a long-distance cyclist, aspiring cob house builder, schema/analytics/algorithm obsessor, and a former senior content writer at Bruce Clay Inc.

See Chelsea’s author page for links to connect on social media.

I am trying to get my website setup and whenever I try to use my domain name to connect I get «404 Not Found»

When I try and reach the site with my IP it works fine.

I am on Debian x64.

Can someone please help me get this resolved.

If you need more information just ask.

Httpd.conf

Apache2.conf

Arnestig's user avatar

Arnestig

2,27517 silver badges30 bronze badges

asked Nov 22, 2012 at 6:04

Nicholas Brown's user avatar

2

Where do you have your website ? On local network or on a hosting service provider?

In any case you need to add your web-server ip to the DNS server (either local or www) depending upon your requirements, without knowing where your webserver is local or global it is difficult to give you an answer

answered Nov 22, 2012 at 6:20

Ravi D's user avatar

Ravi DRavi D

8638 silver badges16 bronze badges

12

Virtual host should look like this:

    <VirtualHost *:80>
        ServerAdmin nicholas_brown@rocketmail.com
        DocumentRoot /home/web/websites/special-faces.net
        ServerName special-faces.net
        ServerAlias www.special-faces.net
        ErrorLog /home/web/website_logs/errorlog.txt
        CustomLog /home/web/website_logs/accesslog.txt common

        <Directory "/home/web/websites/special-faces.net">
            Order allow,deny
            Allow from all
        </Directory>

     </VirtualHost>

If you want to use .htaccess files, add this after the «Allow from all» line:

    Allowoverride all

answered Nov 22, 2012 at 6:17

Kenzo's user avatar

KenzoKenzo

3,4834 gold badges16 silver badges16 bronze badges

1

For Server version: Apache/2.4.16 and later,

<VirtualHost localhost.com:80>
        ServerName localhost.com
        ServerAlias localhost.com
        ServerAdmin webmaster@localhost
        RewriteEngine On

        DocumentRoot /var/www/html
        DocumentRoot /home/<user name where code will be placed>/public_html/html
        <Directory /var/www/html>
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log

        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn

        CustomLog ${APACHE_LOG_DIR}/access.log combinedtimezone

</VirtualHost>

answered Oct 30, 2015 at 17:56

Won Jun Bae's user avatar

Won Jun BaeWon Jun Bae

5,1146 gold badges43 silver badges49 bronze badges

How to Install and Configure Apache for WordPress

How to Install and Configure Apache for WordPress

Learn How to install and configure apache for WordPress. With this guide we will show you how to install and setup Apache for a WordPress installation.

How to Install and Configure Apache for WordPress

Install and Use Apache Tomcat on CentOS 7

Install and Use Apache Tomcat on CentOS 7

Learn how to install and use Apache Tomcat on CentOS 7. Apache Tomcat is a Java Servlet container developed by Apache to which allows you to deploy Java servlets and JSPs. Apache Tomcat also functions as a web server, which is able to support small to medium-sized websites. This tutorial also covers how to install and use the Tomcat Web Admin Manager, which allows you to manage Tomcat and virtual…

Install and Use Apache Tomcat on CentOS 7

Enable CGI Scripts on Apache

Enable CGI Scripts on Apache

Learn how to enable CGI scripts to run on the Apache web server. This tutorial includes step-by-step instructions for adding the necessary Apache configurations to allow CGI scripts to run, and how to set the correct permissions on the directory and CGI files.

Enable CGI Scripts on Apache

Use the ModSecurity Apache Module on a Cloud Server with Ubuntu 16.04

Use the ModSecurity Apache Module on a Cloud Server with Ubuntu 16.04

ModSecurity is a free web application firewall (WAF) which is a simple, powerful way to protect a server against web-based malware and hacking attempts. Learn how to install ModSecurity and the officially-recommended OWASP Core Rule Set (CRS) which will protect a server against malware and hacking in the form of SQL injection, session hijacking, cross-site scripting, Trojans, and many other forms…

Use the ModSecurity Apache Module on a Cloud Server with Ubuntu 16.04

Add and Manage Virtual Hosts on a Plesk Server

Add and Manage Virtual Hosts on a Plesk Server

Learn how to add and manage domains as virtual hosts on a Cloud Server with Plesk. Virtual hosts allow you to host multiple separate websites on the same server, with a separate set of directories for each website.

Add and Manage Virtual Hosts on a Plesk Server

This can also happen when you have a .htaccess file in the document root and that file contains a RewriteRule, as is common with CMS pretty URLs.

The explanation for this behaviour is as follows. The <Location> directives act first, but the handler is not called at this stage. So then the RewriteRule sets a handler, eg to run a PHP script, so SetHandler has no effect in the end.

If this is the cause, find the RewriteRule that is causing the problem(*), and add before it:

RewriteCond %{REQUEST_URI} !=/server-status

This excludes the server-status URI from the RewriteRule in the same way that existing static files may be excluded. Of course what you use in place of /server-status must exactly match the Location chosen, which in the question is instead /status. (Tested on Apache 2.2.22 and Apache 2.4)

Addendum: also note that you can get a 403 trying to read the server-status if the DocumentRoot is not readable by the apache process at all, again because the server-status handler doesn’t have a chance to work.

Addendum 2: if the .htaccess for the Apache default site is frequently overwritten, and the /server-status URL is necessary for eg Munin to work, then creating a <VirtualHost 127.0.0.1:80> stanza including the server-status handler may be administratively simplest.

Addendum 3(*): the RewriteRule that is causing the problem is potentially anything that matches the string /server-status. This may be identifiable because the first parameter will match anything, for example beginning RewriteRule . where the . will match any character, or ^(.*), or otherwise is catching the URI such as .*bstatus$. You may also identify it because it deliberately excludes existing files with !-f.

For example, if WordPress is the main site and you want /server-status to appear on it, and for some reason Addendum 2 above is not applicable, you may want to insert an extra RewriteCond as follows:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/server-status
RewriteRule . /index.php [L]

However, it probably does no harm before any RewriteRule.

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