It is common that you come across the WordPress 404 or “WordPress site permalinks not working” error on your website if it is not appropriately maintained. But there are times when your website is under maintenance, and your visitors will be automatically directed to a 404 error page.
Are you facing a WordPress 404 error or a “WordPress page not found” error? Don’t freak out! We have a solution for you.
- What is a WordPress 404 Error?
- How to Fix 404 Error on WordPress (8 Solutions)
- Clear the Browsing Cache and Cookies
- Set Your Permalinks
- Restore Your .htaccess file
- Set Up a 301 Redirect
- Disabling Plugins/Themes
- Change and Update WordPress URL in Database
- Fix WordPress 404 Error on Local Servers
- Alternative Method
- Conclusion
What is a WordPress 404 Error?
The 404 error is an HTTP response code that occurs when the server cannot find the file or page requested by the user. In response, the web hosting server automatically sends the user an error message, “404 Not Found“.
The WordPress 404 error commonly occurs when:
- You’ve newly migrated your site to a new host.
- You have changed your URL’s permalink structure and haven’t redirected the old URL.
- You don’t have file permissions.
- You have opened an incorrect URL.
- Poorly coded plugin/theme.
Many WordPress themes offer creative layouts & content options to display the 404 error page. Cloudways’ 404 error has a custom design and layout too:
Managed WordPress Hosting Starting from $10/month.
Enjoy hassle-free hosting on a cloud platform with guaranteed performance boosts.
How to Fix 404 Error on WordPress (8 Troubleshooting Solutions)
This tutorial will show you how to quickly fix the 404 Not Found status code. So let’s get started!
1. Clear Browser History & Cookies
The first troubleshooting method you should try is clearing the browser cache and cookies. Or you can try to visit your site in incognito mode.
2. Set Up Your Permalink
If apart from your homepage, your other WordPress website pages give you a 404 page not found error, you can update your permalink settings by following the steps below:
- Log in to your WordPress Dashboard.
- Go to Settings → Permalinks.
- Select the Default settings.
- Click the Save Changes button.
- Change the settings to the previous configuration (the one you selected before Default). Put the custom structure back if you had one.
- Click Save Settings.
Note: If you use a custom structure, copy/paste it into the Custom Base section.
This solution could fix the WordPress 404 not found or “WordPress permalinks not working” error.
If it doesn’t work, you’ll need to edit the .htaccess file in the main directory of your WordPress installation (where the main index.php file resides). 404 errors are also usually due to misconfigured .htaccess files or file permission-related issues.
3. Restore Your .httaccess File
Since .htaccess is a hidden file, you must set all files as visible in your FTP.
Note: It’s always recommended to backup your site before editing any files or pages.
Follow the steps below:
- Log in to your server using an FTP client.
- Download the .htaccess file which is located in the same location as folders like /wp-content/ wp-admin /wp-includes/.
- Open the downloaded file in any text editor.
- Visit the WordPress .htaccess support page and copy/paste the version of the code that is most suitable for your website.
- Save the .htaccess file and upload it to the live server.
For example, if you have Basic WP, use the code below.
# BEGIN WordPress RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteBase / RewriteRule ^index.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] # END WordPress
4. Setup a 301 Redirect
If you have changed the URL of any specific page and haven’t redirected it yet, it’s time to redirect the old URL to your new URL. You may redirect your old post/page via a plugin or a .htaccess file.
If you are comfortable working with .htaccess, add the following code to your .htaccess file. Don’t forget to replace the URLs with your own website.
Redirect 301 /oldpage.html https://www.mywebsite.com/newpage.html
If you prefer the easy way, you may use a plugin to set up a 301 redirect. Follow the steps below:
- Install the Redirection Plugin.
- Go to the WordPress Dashboard.
- Click Tools > Redirection.
- Complete the setup and Add new redirection.
5. Disabling Plugins/Theme
An outdated or poorly coded plugin may be causing the 404 error on your WordPress site. To check this, you must deactivate all your plugins and change your current theme.
Note: All WordPress themes have 404.php files but don’t necessarily have a custom 404 error template file. WordPress automatically uses the 404.php page if the 404 error occurs.
You may access your WordPress files using an FTP like FileZilla. Go to public_html > wp-content and change the plugins folder name to something like myplugins.
Now go back to your browser to check whether the website is working. If the error has been resolved, then any of your plugins could be the culprit.
Note: If it’s not resolved, simply change the myplugins folder name to plugins and move to the next troubleshooting method.
If it’s resolved, change the myplugins folder name to plugins and follow the steps below to check which of your plugin(s) is causing the error.
- Go to your WordPress dashboard.
- Go to Plugins > Installed Plugins.
- Activate each plugin one by one and check if your website is working.
- When you encounter the 404 error, you’d know which plugin caused it.
- Update the plugin or remove it to get rid of the error.
6. Change and Update WordPress URL in Database
You might encounter the following error message on your WordPress website.
“The requested URL was not found on this server. If you entered the URL manually, please check your spelling and try again.”
Fix the error by following the steps below:
- Go to your PHPMyAdmin.
- Navigate to your database name, and select wp-option. For example, blog > wp-option.
- Change the URL, for example, from https://www.abc.com/blog/ to http://localhost/blog.
7. Fix WordPress 404 Error on Local Servers
Many designers and developers install WordPress on their desktops and laptops using a local server for staging purposes. A common problem with local server installations of WordPress is the inability to get permalink rewrite rules to work.
You may try to change the permalinks for posts and pages, but eventually, the website shows the WordPress “404 Not Found” error.
Fixing Errors is Easier With Cloudways
Get rid of WordPress errors with a cloud hosting built to deliver a hassle-free experience with incredible speeds.
Start Free!
In this situation, turn on the rewrite module in your WAMP, XAMPP, or MAMP installation. I am using WAMP in this tutorial. Navigate to the taskbar and find the WAMP icon. After that, navigate to Apache → Apache modules.
It will enable a long list of modules that you can toggle on and off. Find the one called “rewrite_module” and click it, so it is checked.
Then check whether your permalinks are working or not.
8. Alternative Method
If none of the above solutions work, you may try the alternative method to fix the 404 error.
- Navigate to the local server.
- Find the Apache folder, then go to the “conf” folder.
- Navigate to the httpd.conf file.
- Search for a line that looks like:
#LoadModule rewrite_module modules/mod_rewrite.so
- Remove the “#” sign so it looks like this:
LoadModule rewrite_module modules/mod_rewrite.so
Additional tip: PHP workers are used while executing your WordPress site’s code. An ecommerce site that gets 50,000 visitors per month needs a lot more resources than a simple blog with the same amount of traffic.
Conclusion
I hope this guide helped you solve the “WordPress 404 page error” or “WordPress permalinks not working” problem. Have you figured out any other ways to get rid of this problem? Please share your solutions with us in the comment section below.
Also, if you are a WordPress user and want to boost your site, you must try Cloudways WordPress hosting solutions and take advantage of its 3-day free trial.
Frequently Asked Questions
Q. Why am I getting a 404 error?
WordPress 404 errors usually occur when you have removed certain pages from your website and haven’t redirected them to your live pages. Sometimes, these errors may also occur when you have changed a URL of a specific page.
Q. How do I test a 404 error?
You can use multiple tools to test WordPress 404 errors, like Deadlinkchecker. Or you may access Google Analytics to find out which blogs are giving you a 404 error.
Q. How do I fix error 404 on WordPress?
You can fix the error 404 on WordPress by implementing the following solutions:
- Clear the browser cache and cookies
- Set your permalinks
- Make a default .htaccess file
- Set up a 301 redirect
- Disable plugins and themes
- Change and update the WordPress URL in the database
- Fix the error on local servers
Q. How to redirect WordPress 404 pages?
Follow the steps below to redirect WordPress 404 pages:
- Go to your WordPress dashboard.
- Navigate to Tools > Redirection.
- Apply redirection by pasting the broken URL in the source box and the new URL in the Target box.
Q. How to edit a WordPress 404 page?
You may edit a WordPress 404 page by following the steps below:
- Visit your WordPress dashboard.
- Navigate to Appearance > Theme Editor.
- Find the file named “404.php file” and edit the file yourself or with the help of a WordPress developer.
При попытке перехода на страницу какого-либо сайта пользователь может столкнуться с сообщением «The requested URL was not found on this server». Обычно это сигнализирует о наличии проблем с доступом к запрашиваемому пользователю ресурсу, требуя вмешательства администрации сайта для решения возникшей проблемы. Ниже я разберу суть и причины возникшей дисфункции, а также поясню, как её исправить на вашем ПК.
Содержание
- Суть возникшей проблемы
- Как устранить ошибку The requested URL was not found on this server
- Ошибка Requested URL was not found для веб-мастеров
- Заключение
Суть возникшей проблемы
Как я упоминал выше, данная ошибка обычно возникает при попытке пользователя (или веб-мастера) загрузить страницу какого-либо ресурса (в случае веб-мастера это будет его собственный сайт). После набора ссылки на нужный ресурс (или его страницу) в адресной строке браузера пользователь получает вышеприведённое сообщение, в переводе звучащее как «Затребованный URL не найден”.
Сообщение об отсутствии затребованного URL обладает различной вариативностью, к примеру, оно может выглядеть как «The requested URL .html was not found on this server». Также в тексте сообщения может упоминаться довольно «популярная» в сети ошибка 404.
Причины ошибки могут быть следующими:
- Пользователь неверно ввёл адрес сайта в адресной строке веб-навигатора;
- Запрашиваемая страница удалена или перемещена на другой интернет-адрес, или сам ресурс не работает по различным причинам;
- Веб-мастер неверно настроил файл конфигурации своего ресурса;
- Имеются проблемы в работе ДНС-серверов;
- Брандмауэр, а также вирусные или антивирусные программы блокируют доступ к нужному ресурсу;
- В функционал браузера установлены различные сетевые расширения или дополнения, препятствующие доступу к нужной интернет-странице.
Как устранить ошибку The requested URL was not found on this server
Чтобы избавиться от ошибки рекомендую сделать следующее:
- Проверьте корректность набранной вами ссылки. Даже один не верно набранный символ может вызывать появление данной ошибки. Внимательно проверьте правильность набранного вами линка, и если всё хорошо, тогда идём дальше;
- Перегрузите проблемную страницу (поможет стандартное нажатие на клавишу F5);
- Очистите историю, куки, кэш вашего веб-навигатора. Например, в Хром для этого необходимо нажать на кнопку настроек браузера (три точки вверху слева), в открывшемся окне выбрать «Настройки», и в них найти опцию «Очистить историю»;
- Подождите некоторое время. Вполне возможно, что на сайте проводятся различные технические работы, и через некоторое время запрашиваемая страница станет доступна в полном объёме, что поможет решить ошибку requested URL not found;
- Поищите нужную страницу через популярные поисковые системы (Гугл, Яндекс, Бинг и другие). Если вы помните какие-то словосочетания из контента необходимой вам страницы, тогда стоит поискать её через поисковики по указанным словосочетаниям;
- Используйте альтернативные публичные ДНС-сервера, доступные в сети. К примеру, чтобы настроить ПК на использование подобных серверов от Гугл, необходимо нажать на Win+R, и там набрать ncpa.cpl. В открывшемся перечне сетевых подключений найти ваше интернет-подключения, навести на него курсор, щёлкнуть ПКМ, и выбрать «Свойства». В списке имеющихся сетевых компонентов найти «IP версии 4», дважды кликнуть на нём, и внизу ввести ДНС адреса так, как указано на картинке.
Затем нажмите на «Ок», и перезагрузите ваш PC, это может помочь избавиться от ошибки requested URL not found.
- Временно отключите ваш антивирус и файервол, дабы убедиться, что они не блокируют вам доступ к нужному ресурсу;
- Проверьте ваш PC на наличие зловредов (к примеру, с помощью известного «ДокторВеб Кюрейт»);
- Деактивируйте (удалите) с вашего навигатора лишние проблемные расширения и дополнения;
- Уведомьте администрацию сайта об имеющейся проблеме. Возможно, последняя просто не в курсе возникающих у пользователей проблем с функционалом ресурса. Напишите ей письмо, приведите ссылку на проблемную страницу, после чего ожидайте вероятного исправления возникшей проблемы.
Ошибка Requested URL was not found для веб-мастеров
В данном случае давать универсальные советы довольно сложно, так как каждая такая ошибка на ресурсе веб-мастера имеет индивидуальный характер, и решается за счёт таких же индивидуальных рецептов. К примеру, попробуйте выполнить следующее:
- При работе с APACH попробуйте добавить «8080» в строку ServerName localhost, содержащуюся в файле apacha/conf/httpd.conf. Таким образом, данная строка будет выглядеть как:
ServerName localhost:8080
Перезагрузите ПК и попробуйте выполнить вход на нужную вам страницу;
- Проверьте корректность настроек в файле .htaccess. Сохраните данный файл заново, это может помочь избавиться от проблемы the requested URL was not found;
- При работе с PHP проверьте наличие файла index.php и права доступа к нему на вашем сайт (к примеру, разрешения к такому файлу могли быть выставлены на “000”, что неверно). При необходимости, установите корректные права для данного файла.
Заключение
Появление ошибки «The requested URL was not found on this server» обычно вызвано проблемами доступа к нужной странице на запрашиваемом пользователем сервере. Для решения проблемы рекомендуется в первую очередь проверить корректность ввода набранного вами линка. Если в этом случае ошибок не выявлено, используйте другие советы из перечисленного выше перечня, которые позволят решить проблему с проблемной ссылкой на запрашиваемом вами ресурсе.
Опубликовано 28 марта 2018 Обновлено 16 мая 2021
Ошибки с загрузкой страницы, наверное, самые распространенные во всем мире. Как часто еще вчера загружающийся сайт внезапно перестает отображаться. На все попытки получить к нему доступ ответом становится уже легендарное сообщение «404 Not Found». Для владельцев сайтов или блогов больше знакома фраза «Not found: The requested url was not found on this server». В обоих случаях контент на интернет ресурсе перестает отображаться. Но если в первом случаи можно найти альтернативу, то с собственным сайтом все нужно исправлять как можно быстрее.
Содержание
- Что это за ошибка
- Пробуем исправить проблему
- Заключение
Что это за ошибка
«404 Not Found» — это ошибка, сообщающая что запрашиваемой страницы не существует, она удалена, перемещена, переименована, либо на стороне сервера есть проблемы: повреждена база данных, неправильно настроены быстрые ссылки и т.д.
Ошибка «404 Not Found: The requested URL»
Как вы поняли, причин сбоя, как таковых, может быть довольно много. Сюда же стоит отнести банально неправильны ввод, при прописывании адреса. Далее следует мимолетный сбой сервера, разные технические работы со стороны сервера, владельцы решили произвести оптимизацию и убрали все не нужное, переноса сайта на другую платформу.
Пробуем исправить проблему
Решением становиться несколько простых, но действенных советов. Вообще тут нет трудных решений, ведь сайт, на который вы пытаетесь попасть, принадлежит другим людям, а они в свою очередь могут делать с ним все что угодно.
- Почистите историю браузера и обновите страницу несколько раз через CTRL+F5.
- Проверьте правильность написания адреса. Иногда один упущенный символ становиться проблемой. В качестве альтернативы вбейте адрес или название сайта в поисковике, он уже самостоятельно найдет более удобный путь.
- Перезапустите службу DNS-клиент на компьютере. Она находится в списке всех служб.
Перезапуск службы DNS-клиент в Windows
- При закрытом браузере почистите кэш-данные и записи реестра в Windows — CCleaner вам в помощь.
CCleaner — очищаем кэш и реестр
- Попробуйте сменить ПК на планшет или телефон. Нужно установить общую работу интернет ресурса, ведь возможно он временно все-таки перестал работать. Иногда такое случается только с отдельными страницами, а, к примеру, форум или блог будет открываться в стандартном режиме.
- Воспользуйтесь сторонними утилитами, сервисами для определения работоспособности ссылки. Такие специальные службы есть в Яндекс и Google. Просто забейте необходимый запрос в поисковик.
- Смиритесь с тем, что сайт перестал работать. Как вариант попробуйте найти его разработчиков и напрямую поинтересоваться у них о возобновлении работы. Иногда меняется сервер или происходят DDoS-атаки. Посетите аналогичную группу в социальной сети, они сейчас есть почти у всех известных сайтов, задайте там вопрос о загрузке интернет-ресурса.
Помните главное — в большинстве случаев, проблема на стороне сервера и вы с этим поделать ничего не можете.
Эта ошибка очень часто постигает тех веб-разработчиков, кто использует для своего сайта WordPress. Хотя встречается во всех других платформах так же. Иногда сам пользователь не осознавал того внес не совсем корректные изменения, что характерно для меню «Постоянные ссылки».
Особых советов веб-мастерам давать не хочется, но по собственному опыту замечу, что на моем первом блоге, была установлены бесплатная тема WordPress. Из-за её дыр меня постоянно атаковали вирусы, которые сносили данные в .htaccess. Проблему решил заказом антивирусной проверки сайта и установкой прав доступа администратора к файлу.
Заключение
Помните про то, что альтернативный источник в интернете можно найти практически всегда. Иногда лучше найти другой сайт, чем пытаться разобраться в возникшей ошибке, которая с большой долей вероятности от вас не зависит. Надеюсь вы поняли, что это за ошибка в браузере Not found: The requested url was not found on this server и как её исправить.
Of the many potential errors you might see on your WordPress site, Error 404 Not Found is one of the tamer ones. But that doesn’t mean it isn’t frustrating when you or your visitors try to browse your site and keep running into the Error 404 Not Found message. 😒 That’s the last thing you want first-time potential customers seeing from your brand. A 404 error can also be an indicator to you that something has changed or moved and a 301 redirect probably needs to be added for SEO.
In this post, we’re going to try to help you get your site working again by explaining a few things:
Prefer to watch the video version?
What is the Error 404 Not Found?
The Internet Engineering Task Force (IETF) defines the error 404 Not Found as:
The 404 (Not Found) status code indicates that the origin server did not find a current representation for the target resource or is not willing to disclose that one exists. A 404 status code does not indicate whether this lack of representation is temporary or permanent; the 410 (Gone) status code is preferred over 404 if the origin server knows, presumably through some configurable means, that the condition is likely to be permanent.
Whenever you, or one of your visitors, visit your website, your browser sends a request to the web server and receives back data including something called an HTTP header. The HTTP header includes HTTP status codes to explain “what happened” with the request.
Most of the time, the request works perfectly and you never actually see the HTTP status code (unless you go looking). But if something goes wrong, your web browser will usually display a message with the HTTP status code to indicate the exact problem.
Just like other error messages (500 error, 502 error, 503 error, 504 error, etc.), the Error 404 Not Found message is the result of that process.
What Does Error 404 Not Found Actually Mean?
Basically, it means that the client (your, or your visitor’s, web browser) was able to successfully connect to the host (your website’s server), but it was unable to find the actual resource that was requested (e.g. a specific URL or filename).
For example, if someone tries to access yoursite.com/post-name
but you don’t have any content with the slug post-name
. The visitor will then see a 404 error because, even though your web server is functioning normally, the resource that was requested doesn’t exist.
It’s not just posts or pages either, any asset missing can generate a 404 error on the server, such as a missing image file, missing JavaScript, missing CSS, etc.
What Causes Error 404 Not Found on WordPress?
If you see this error on all of your site’s content, it’s typically due to an issue with your WordPress site’s permalinks. If you only see it on individual pieces of content, though, it’s most likely because you changed a piece of content’s slug without setting up a redirect.
Additionally, the 404 error isn’t always a bad thing – it’s only bad when it’s interfering with usability. And sometimes things are just out of your control!
For example, sometimes a person might just type the wrong URL in their address bar. In that case, they’ll still see a 404 error, but there’s no actual problem with how your site is configured. This is actually the desired response, and you can create your own custom 404 page to help get visitors to the right spot (we’ll show you how later on).
Error 404 Not Found Variations
Because different browsers display error messages differently, you might see a different message for this error. Other common variations include:
- “Error 404”
- “404 Not Found”
- “HTTP Error 404”
- “Not Found”
- “Page Not Found”
- “The requested URL was not found on this server.”
- “The page cannot be found”
- “We can’t find the page you’re looking for.”
- “The requested URL /~ was not found on this server. That’s all we know.
The Error 404 Not Found message is also unique in that many sites will actually create a custom page to address the error, rather showing one of the messages above. Some WordPress themes also include custom 404 pages by default. For that reason, you might not actually see the error message at all because many sites will use funny or creative 404 pages instead.
Below is an example of our own 404 page at Kinsta. We include a search box and some of our recent blog posts to help visitors find what they might have been looking for. Always include search functionality on your 404 page.
Error 404 Not Found Impact on SEO
Error 404 Not Found doesn’t have any inherent negative impact on SEO. But it might have a negative impact depending on the reason for why the error is happening.
For example, if a visitor just mistypes a URL and sees a 404 error – there won’t be a negative impact on SEO. But if you have individual errors because of broken URLs, that will inhibit Google’s ability to properly crawl your site and have a negative SEO effect in that way.
Additionally, if a permalink issue is causing sitewide 404 errors, Google won’t be able to crawl any of your site’s content. In other words, always fix your 404 errors as soon as possible.
Error 404 Not Found Impact on Site Performance
Many don’t realize it, but sites that generate a lot of 404 errors can easily run into performance issues, as these responses aren’t typically cached. We saw this a lot on larger sites and it can be a big problem if you accidentally promote or get a surge of viral traffic to a 404 page. To minimize the impact of 404 requests on site performance, we automatically cache 404 pages for 15 minutes. If you create a new page with the same URL as the cached 404 page, we’ll automatically purge the cache so your visitors will be able to see the new page immediately. This means your site will be protected from PHP and CPU spikes caused by traffic to dynamic 404 pages.
You are probably generating more 404 errors than you think! Our MyKinsta analytics tool can help you determine the exact amount (as seen below).
You can also quickly see what the top 404 errors are. In this example below, you can see the site is missing some mobile icons, such as /apple-touch-icon.png
. These are most likely in a theme or plugin’s code that is getting queried, but the actual icons were never added. Therefore, the server generates a 404 error as it can’t find the resources.
You can also check 404 errors in Google Search Console or install a third-party plugin such as Redirection which logs 404 errors. However, remember that plugins like these also have an impact on performance. It’s much better to rely on a server-level tool. That’s why we provide these tools for all Kinsta clients.
The reason these errors are bad is that many 404 pages are very resource intensive. For large sites, you’ll want to avoid a heavy 404 page. Create a simple 404 template that avoids querying the database any further if possible.
How to Fix Error 404 Not Found on WordPress
Below, we’ll cover a couple different methods for how to fix the Error 404 Not Found message, depending on whether it’s happening sitewide or to specific content.
Update Your WordPress Site’s Permalinks
If you’re experiencing sitewide 404 errors when trying to access content, the most likely cause is an issue with your permalinks (or your .htaccess file, if your host uses Apache). If you’re a Kinsta client, we utilize Nginx, so you can rule out the .htaccess file as a possible cause.
The easiest way to fix this is to update your permalink settings through the WordPress dashboard. All you need to do is go to Settings → Permalinks and click Save Changes (you don’t need to make any changes – clicking Save Changes is enough).
Set Up 301 Redirects For Moved or Renamed Content
If you’re experiencing 404 errors on a specific piece of content, the issue is likely that you:
- Changed the URL slug for that content.
- Moved that piece of content manually, e.g. by deleting the existing post and pasting it into a new post.
Users then try to access the content at the old location and see a 404 page instead of the resource they were expecting. The best way to fix this is to automatically redirect anyone who tries to access the old location to the new location. That way, they’ll make it to the right spot without any 404 errors. It’s also good for SEO. If you move or rename a post without adding a redirect, you lose all the domain authority attached to the backlinks pointed at that post.
WordPress by default will attempt to redirect changed/moved content. But it doesn’t always work and you should never rely on WordPress for this functionality. But don’t worry, there are several easy ways to set up redirects in WordPress:
First, you can use the free Redirection plugin to manage redirects from your WordPress dashboard. Once you’ve installed and activated the plugin, go to Tools → Redirection and enter the 404 page URL in the Source URL box and the new location of the content in the Target URL box:
If you’re hosting with Kinsta, you can also manage redirects from the MyKinsta dashboard. Using Kinsta’s tool is actually a better way to go about it as the rules are implemented at the server level, which is a much more optimal way in terms of performance. It also means one less third-party plugin you have to worry about.
Go to the site you want to manage. Then, click on the “Redirects” tab. To add a new redirect, click the large “Add Redirect Rule” button:
Finally, if your host uses the Apache server, you can use .htaccess to set up redirects. The .htaccess Generator site can help you generate the proper code to add to your site’s .htaccess file.
How to Create Your Own Error 404 Not Found Page
While you can do your best to prevent 404 errors by following the tips above, it’s impossible to entirely eliminate 404 errors because some things are just plain outside your control. It’s not uncommon for small WordPress sites to have thousands of 404 errors every month.
For example, if a visitor mistypes the URL, or if another website links to a page that doesn’t exist, people are going to get 404 errors no matter what.
To provide a more user-friendly error page, you can use one of the many 404 page plugins. For example, the free 404page plugin lets you set up a custom 404 error page with:
- A search box
- Important links
- Contact information
Another important feature of the 404page plugin is that it doesn’t create redirects. A 404 page should never be redirected to a physical page such as yoursite.com/404
. The 404 error should always be generated dynamically on the page in question.
By including these elements, you give visitors the tools they need to find their way to the right page. But remember, keep your 404 page light for better performance. Only include what is absolutely needed.
How to Monitor 404 Errors Going Forward
Going forward, it can be beneficial to pay attention to which requests are causing 404 errors at your site. This can help you:
- Find broken links that are sending people to a non-existent resource (these could be internal links or external links from other sites). You’d then want to do your best to fix those links if at all possible.
- See which pages Google is having trouble crawling. You’d then want to figure out why Google is trying to crawl a non-existent page and set up a redirect if needed.
- Troubleshoot performance related issues with 404 errors.
Option 1 – Google Analytics
If you use Google Analytics, you can set up a custom report to track 404 errors from external links. Rebelytics has a good tutorial on the topic.
Option 2 – WordPress Plugin
If you want to use a WordPress plugin, the aforementioned Redirection plugin can help you monitor for 404 errors from your WordPress dashboard.
Option 3 – Third-Party Audit Tool
You can also use a third-party audit tool like Ahrefs to monitor for 404 errors on your WordPress site. You can even set this up to run on a schedule.
Option 4 – Google Search Console
Lastly, you can track 404 errors that Google’s crawlers encounter in Google Search Console. Once you’ve verified your site with Google Search Console, go to Crawl → Crawl Errors → Not found to view a list of 404 errors that Google has encountered. This is by far one of the easiest ways. It’s also the best in terms of performance because it requires no third-party plugins or additional scanning against your site. Google’s bots are already crawling your site on a regular basis, so why not simply take advantage of the data they already provide? 😉
Summary
Unfortunately, 404 errors will happen on your site whether you like it or not. The larger your WordPress site is, the more you’ll start seeing. We recommend getting a good workflow together for how you monitor these types of errors and go about fixing them. 404 errors are never good for visitors, your brand, and Google doesn’t like to see them either.
Have any other tips or questions regarding the Error 404 Not Found message or how it impacts your WordPress site? Let us know below in the comments.
Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:
- Easy setup and management in the MyKinsta dashboard
- 24/7 expert support
- The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
- An enterprise-level Cloudflare integration for speed and security
- Global audience reach with up to 35 data centers and 275 PoPs worldwide
Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.
You have built an Angular app and created a production build with ng build --prod
You deploy it to a production server. Everything works fine until you refresh the page. The app throws The requested URL was not found on this server
message (Status code 404 not found). It appears that angular routing not working on the production server when you refresh the page.
The error appears on the following scenarios
- When you type the URL directly in the address bar.
- When you refresh the page
- The error appears on all the pages except the root page.
- The error occurs only if you are using HTML 5 Routing or PathLocationStrategy
This is due to the fact that the Angular is a SPA (Single Page Application) framework.
Table of Contents
- Reason for the requested URL was not found on this server error
- Workaround
- IIS Server
- Apache
- Nginx
- References
In a Multi-page web application, every time the application needs to display a page it has to send a request to the webserver. You can do that by either typing the URL in the address bar, clicking on the Menu link/ button. Every such action results in a new request being sent to the Web server. For each request, a corresponding page must exist on the server. The server locates that page and returns it back to the client.
But in Angular Apps, the app starts when the main page (index.html
) is loaded. Any subsequent requests do not reload the page but only load a part of the page. The requests are not sent to the server but handled by the Angular router at the client-side. You can read more about it from the article Angular bootstrap process
For Example, when you request for example.com
the request is sent to the server, which returns the index.html
.This will bootstrap the Angular.
Now when you click on example.com/products
, the request is not sent to the server but handled at the client-side by the Angular Router. The Router loads the component associated with the products
route. The products
component may send an HTTP request to fetch the list of products to display. But the request to display the products
page is never sent to the server.
What happens when somebody types the example.com/products
in the address bar or refreshes the page. Now the request to fetch the products page is sent to the server. Since there is no products page available in the server it returns the The requested URL was not found on this server or 404 error page
Workaround
The workaround to this problem is to instruct the server to load the index.html
no matter what. So when the request comes to example.com/products
page, the server serves the index.html
page. This bootstraps the Angular app and the Angular router is smart enough to read the requested URL and load the products
component.
To instruct the server to load the index.html
for every request require a configuration change at the Web server level. The configuration settings depend on the server used.
IIS Server
First, install the IIS URL Rewrite module. Copy the following to web.config file
to the root of the application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<?xml version=«1.0» encoding=«utf-8»?> <configuration> <system.webServer> <rewrite> <rules> <rule name=«Angular Routes» stopProcessing=«true»> <match url=«.*» /> <conditions logicalGrouping=«MatchAll»> <add input=«{REQUEST_FILENAME}» matchType=«IsFile» negate=«true» /> <add input=«{REQUEST_FILENAME}» matchType=«IsDirectory» negate=«true» /> </conditions> <action type=«Rewrite» url=«./index.html» /> </rule> </rules> </rewrite> </system.webServer> </configuration> |
Apache
Add a rewrite rule to the .htaccess
file as shown.
RewriteEngine On # If an existing asset or directory is requested go to it as it is RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} —f [OR] RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} —d RewriteRule ^ — [L] # If the requested resource doesn’t exist, use index.html RewriteRule ^ /index.html |
Nginx
Add the following try_files
rules to the Nginx configuration file to redirect every request to serve index.html
try_files $uri $uri/ /index.html; |
References
Routed apps must fallback to index.html
Angular Bootstrap Process
Location strategies in Angular
Angular Router
The error indicates that while the server itself is reachable, the specific page showing the error is not
Updated on December 7, 2022
A 404 error is an HTTP status code that means that the page you were trying to reach on a website couldn’t be found on their server.
To be clear, the error indicates that while the server itself is reachable, the specific page showing the error is not.
404 Not Found error messages are frequently customized by individual websites. So, keep in mind that the error might show up in just about any way imaginable depending on what website it’s shown from.
How You Might See the 404 Error
Here are some common ways in which you might see the HTTP 404 error displayed:
- 404 Error
- 404 Not Found
- Error 404
- The requested URL [URL] was not found on this server
- HTTP 404
- Error 404 Not Found
- 404 File or Directory Not Found
- HTTP 404 Not Found
- 404 Page Not Found
- Error 404. The page you’re looking for can’t be found.
These error messages can appear in any browser or any operating system. Most display inside the browser window just as web pages do.
In Internet Explorer, the message The webpage cannot be found usually indicates an HTTP 404 error but a 400 Bad Request error is another possibility. You can check to see which error IE is referring to by checking for either 404 or 400 in the title bar.
404 errors received when opening links via Microsoft Office applications generate a The Internet site reports that the item you requested could not be found (HTTP/1.0 404) message inside the MS Office program.
When Windows Update produces one, it appears as a code 0x80244019 or as the message WU_E_PT_HTTP_STATUS_NOT_FOUND.
Cause of HTTP 404 Errors
Technically, an Error 404 is a client-side error, implying that it’s your mistake, either because you typed the URL incorrectly or the page has been moved or removed from the website and you should have known.
Another possibility is if a website has moved a page or resource but did so without redirecting the old URL to the new one. When that happens, you’ll receive a 404 error instead of being automatically routed to the new page.
Microsoft IIS web servers sometimes give more specific information about the cause of 404 Not Found errors by suffixing a number after the 404, as in HTTP Error 404.3 — Not Found, which means MIME type restriction.
How to Fix the 404 Not Found Error
-
Retry the web page by pressing F5, clicking/tapping the refresh/reload button, or trying the URL from the address bar again.
The 404 Not Found error might appear for several reasons even though no real issue exists, so sometimes a simple refresh will often load the page you were looking for.
-
Check for errors in the URL. Often times this error appears because the URL was typed wrong or the link that was selected points to the wrong URL.
-
Move up one directory level at a time in the URL until you find something.
For example, if www.web.com/a/b/c.htm gave you the 404 Not Found error, move up to www.web.com/a/b/. If you get nothing here (or an error), move up to www.web.com/a/. This should lead you toward what you’re looking for or at least confirm that it’s no longer available.
If you have moved all the way up to the website’s home page, try to run a search for the information you’re looking for. If the site doesn’t have a search function, try navigating to the page you want using category links to dig deeper into the site.
-
Search for the page from a popular search engine. It’s possible that you simply have the entirely wrong URL in which case a quick Google or Bing search should get you where you want to go.
If you do find the page you were after, update your bookmark or favorite to avoid the HTTP 404 error in the future.
-
Clear your browser’s cache if you have any indication that the 404 message might just be yours. For example, if you can reach the URL from your phone but not from your tablet, clearing the cache on your tablet’s browser might help.
You might also consider clearing your browser’s cookies or at least the one(s) involved with the website in question if clearing the cache didn’t work.
-
Change the DNS servers used by your computer, but usually only if an entire website is giving you a 404 error, especially if the website is available to those on other networks (e.g., your mobile phone network or a friend in another city).
404s on an entire website isn’t particularly common unless your ISP or government filters/censors websites. No matter the reason, if it does happen, giving another set of DNS servers a try is a good step to take. See our Free and Public DNS Servers List for some alternatives and instructions on doing this.
-
Contact the website directly. If they’ve removed the page you’re after then the 404 error is completely legitimate and they should be able to tell you that. If they’ve moved the page and are generating errors instead of redirecting visitors to the new page, they’ll be happy to hear from you so they can go fix it.
-
Finally, if all else fails, wait. No, it’s not fun, but it might be your only course of action, especially if you’re confident the 404 error shouldn’t be happening (i.e., the page really should be at the URL you have and others are having the same problem and find it equally strange).
Errors Similar to Error 404
Some other client-side error messages related to the 404 Not Found error include 400 Bad Request, 401 Unauthorized, 403 Forbidden, and 408 Request Timeout.
Several server-side HTTP status codes also exist, like the popular 500 Internal Server Error. You can see all of them in our HTTP Status Code Errors list.
FAQ
-
How do I fix error 404 messages on my website?
If you’re aware of pages on your website with broken links, redirect or correct them. If a 404 error appears due to a deleted page, consider restoring or redirecting it to new and related content.
-
How do I fix error 404 on WordPress?
If you use WordPress, 404 errors often pop up because of redirect conflicts or permalink issues. Fix broken links for individual pages or posts. Visit the WordPress dashboard and update permalink settings if it’s a site-wide problem.
Thanks for letting us know!
Get the Latest Tech News Delivered Every Day
Subscribe
Ошибка 404, либо Error 404 Not Found — ошибка, которая появляется, если браузеру не удалось обнаружить на сервере указанный URL.
Сообщение об ошибке 404
Что означает ответ 404
Error 404 Not Found отображается по-разному: «HTTP 404 не найден», «Ошибка 404 Not Found», «404 Страница не найдена». Смысл надписи всегда остаётся тем же: страница отсутствует либо просто не работает. Not Found в переводе означает «не найдено».
Ошибка 404 — классический код ответа по протоколу HTTP. Он свидетельствует, что связь с сервером установлена, но данных по заданному запросу на сервере нет.
Однако если просто ввести в поисковую строку произвольный набор символов, то браузер не покажет ошибку 404 Not Found — появится сообщение, что установить соединение с конкретным сервером невозможно.
Разберёмся в техническом формировании ответа Error 404 Not Found.
Техническая сторона вопроса. При связи по HTTP браузер запрашивает указанный URL и ждёт цифрового ответа. То есть любой запрос пользователя направляется на сервер размещения искомого сайта. Когда браузеру удаётся связаться с сервером, он получает кодированный ответ. Если запрос корректный и страница найдена, отправляется ответ с кодом 200 OK, что соответствует благополучной загрузке. При отсутствии страницы отправляется ответ об ошибке.
Что значит код «404». В ответе 404 первая четвёрка указывает на то, что запрос был чрезмерно длительным или в самом адресе была ошибка. Ноль предполагает синтаксическую неточность. Завершающая цифра кода отображает конкретную причину ошибки — «4» означает отсутствие данной ссылки.
Какие ещё ошибки бывают. Ошибку 404 не нужно путать с другими ответами, которые указывают на невозможность связи с сервером. Например, ошибка 403 сообщает, что доступ к URL ограничен, а ответ «Сервер не найден» свидетельствует, что браузер не смог обнаружить место размещения сайта.
Google на 404 странице сообщает о возможных причинах ошибки
Причины ошибки
Причины, по которым HTTP возвращает ответ 404 Not Found:
- Неверный адрес. К примеру, при ручном наборе пользователь допустил опечатку в адресе либо ссылка ведёт на несуществующую страницу. При этом домен должен быть написан верно. Если пользователь ошибется в названии домена, страница вообще не загрузится (без показа ошибки).
- Битая ссылка. Это нерабочий URL, который никуда не ведёт. Данный вариант иногда возникает при внутренней перелинковке. К примеру, раньше страница существовала, а потом её удалили и забыли убрать ссылку.
- Удалённая страница. Когда пользователь попытается перейти на удалённую с сервера страницу, он также увидит ошибку 404. Ссылка для перехода может сохраниться в браузерных закладках или на сторонних ресурсах.
- Неправильный редирект на страницу с изменённым адресом. Допустим, в процессе редизайна URL изменили, но оставили без внимания связанные ссылки.
- Неполадки на сервере. Это самый редкий вариант.
В большинстве ситуаций ошибка 404 отображается, когда не удаётся обнаружить нужную страницу на доступном сервере.
Причины отсутствия страницы на сайте бывают разными
Возможные последствия для сайта
Нужно ли считать 404 ошибку опасной для сайтов? Кажется, что нет ничего плохого в том, что пользователь не смог открыть одну веб-страницу. Однако если такая ситуация будет повторяться регулярно, это чревато оттоком аудитории. Одни пользователи решат, что сайт вовсе не существует. Другие подумают, что лучше не заходить на сайт, который работает с ошибками. Третьи будут игнорировать ресурс, на котором не смогли получить обещанную информацию.
Поисковые системы относятся к Not Found более лояльно. Например, Google отмечает, что 404 страницы не влияют на рейтинг. Но если при индексации роботы будут находить все больше ошибочных страниц, вряд ли это приведёт к более высокому ранжированию.
Если вы хотите улучшить взаимодействие с посетителями, важно найти и исправить все ошибки 404 на сайте.
Как выявить ошибку
На небольшом ресурсе легко проверить работоспособность ссылок вручную. Но если на сайте сотни и тысячи страниц, без дополнительного софта не обойтись. Есть немало сервисов и программ, позволяющих находить битые ссылки. Рассмотрим некоторые из них.
Search Console Google
Консоль поиска Google позволяет находить страницы с ошибкой 404 за несколько кликов:
- Войдите в учётную запись Google и перейдите в Search Console.
- Откройте раздел «Ошибки сканирования» → «Диагностика».
- Кликните на «Not Found».
Чтобы получить список страниц с ошибками, подтвердите права на ресурс — добавьте проверочную запись TXT в записи DNS регистратора домена. Такая запись не повлияет на работу сайта. Подробнее о процедуре подтверждения, читайте в справке Google.
Для использования Search Console Google нужно подтвердить свои права на сайт
Яндекс Вебмастер
Сервис для вебмастеров от Яндекса поможет быстро найти все ошибки 404:
- Откройте Вебмастер после авторизации в Яндекс-аккаунте.
- Выберите «Индексирование» → «Доступные для поиска страницы» → «Исключённые страницы».
- В выданном списке выберите фильтр «Ошибка HTTP: 404».
Чтобы использовать Яндекс.Вебмастер, также нужно подтвердить право владения сайтом — добавить метатег в HTML-код главной страницы.
Для входа в Вебмастер авторизуйтесь в Яндексе
Screaming Frog
Для начала загрузите и установите программу на компьютер. После запуска добавьте URL проверяемого сайта и начните поиск проблем. Неработающие ссылки можно искать даже в бесплатной версии.
Инструмент SEO-паук в Screaming Frog помогает найти технические неисправности сайта
SiteAnalyzer
Эта бесплатная десктопная программа позволяет обнаружить технические погрешности на сайте. SiteAnalyzer быстро отыщет нерабочие и несуществующие ссылки.
SiteAnalyzer бесплатно найдёт неработающие URL
Как исправить ошибку Not Found
Выбор конкретного решения зависит от причины ошибки:
- Ссылка ведёт в никуда из-за неверного URL. Для решения проблемы замените ошибочную ссылку на правильный адрес, чтобы сервер отдавал код 200 OK.
- Битая ссылка. Подобная ситуация не редкость при внутренней перелинковке страниц. К примеру, ссылка есть, а саму страницу давно удалили. Решений два: удалить ссылку или заменить её на другую.
Удалять и менять ссылки вручную удобно только на небольших сайтах. Исправление ошибок на крупных порталах лучше автоматизировать. Например, с помощью специальных плагинов для внутренней перелинковки (Terms Description, Dagon Design Sitemap Generator) и для автоматического формирования адресов страниц (Cyr-To-Lat).
Чтобы ошибки 404 появлялись как можно реже, достаточно соблюдать простые рекомендации:
- Не присваивайте сложные адреса основным разделам сайта. Это снизит число ошибок, связанных с опечатками в URL.
- Не меняйте адреса страниц слишком часто. Это неудобно для пользователей и вводит в заблуждение поисковых роботов.
- Размещайте сайт на надёжном сервере. Это предотвратит ошибки, возникающие из-за неработоспособности сервера.
Мы разобрались, как найти и исправить ошибки Not Found внутри сайта. Но неработающая ссылка может быть расположена и на стороннем ресурсе. Допустим, когда-то на другом сайте разместили рекламную публикацию со ссылкой на определённую страницу. Спустя какое-то время страницу удалили. В этом случае появится ошибка 404. Устранить её можно, связавшись с администрацией ссылающегося сайта. Если же удалить/исправить ссылку нельзя, постарайтесь использовать ошибку с выгодой.
Как сделать страницу 404 полезной
Грамотно оформленная страница с ошибкой Error 404 Not Found — действенный инструмент конвертации посетителей. Ограничений по использованию страницы с ошибкой 404 нет. При этом практически все CMS позволяют настраивать дизайн этой страницы.
Что публиковать на странице 404:
- меню с кликабельными ссылками;
- ссылку на главную страницу;
- анонс последних публикаций;
- контакты для обратной связи.
При оформлении страницы-ошибки желательно опираться на рекомендации поисковиков:
- Яндекс настоятельно рекомендует, чтобы страница контрастировала с основным содержанием сайта — иные цвета, другие графические приёмы либо их отсутствие. Необходимо чётко и понятно объяснить пользователю, что запрошенной страницы не существует и предложить другое решение.
- Google советует придерживаться единого стиля оформления. Но также рекомендует понятно рассказать об ошибке и предложить полезные материалы.
Главное — по возможности отказаться от стандартной страницы 404. Подумайте, как привлечь внимание пользователя. Расскажите ему об отсутствии искомой страницы и предложите взамен что-то полезное или интересное.
Примеры оформления страниц 404
Designzillas
Мультяшная страница креативной студии привлекает внимание и её хочется досмотреть до конца. Если прокрутить страницу, можно увидеть, как из яйца вылупится дракон. При этом на странице есть ссылки на все основные разделы сайта.
Меню на сайте Designzillas есть и на 404 странице
Domenart Studio
Веб-студия «Домен АРТ» использует красочную страницу 404, оформленную в единой стилистике ресурса. Заблудившимся пользователям предлагают попробовать ещё раз ввести адрес или перейти в нужный раздел.
Контакты, поиск, меню — и всё это на 404 странице Domenart Studio
E-co
«Эко Пауэр», дистрибьютор производителя источников питания, демонстрирует короткое замыкание как символ ошибки. Посетителям предлагают перейти на главную.
Ошибка 404 «Эко Пауэр» выглядит как страница входа
Дом со всем
Компания «Дом со всем», занимающаяся бурением скважин, разместила на странице 404 свои контакты и перечень услуг. Со страницы можно перейти в любой раздел сайта или заказать обратный звонок. С таким наполнением посетителю не нужно искать дополнительную информацию где-то ещё.
Компания «Дом со всем» предлагает заказать обратный звонок
Kualo
Страница 404 на веб-хостинге Kualo может заставить пользователя забыть, зачем он сюда пришёл. Увлекательная игра притягивает внимание. В конце игры посетителю предлагают посмотреть сайт хостинга.
На странице Kualo можно просто поиграть и заработать скидки
Рано или поздно с ошибкой 404 сталкивается большинство сайтов. При регулярной проверке можно своевременно исправить неработающие ссылки, чтобы в ответ пользователи получали код 200 OK. Но для крупного ресурса лучше настроить оригинальную страницу, которая будет отображаться при появлении ошибки Not Found и подскажет посетителям, что делать дальше.