404 not found nginx что это значит
Перейти к содержимому

404 not found nginx что это значит

  • автор:

Support

Find answers, guides, and tutorials to supercharge your content delivery.

Fixing a 404 Not Found Nginx Error

Fixing a 404 Not Found Nginx Error

What does a 404 Not Found error mean?

A 404 Not Found error occurs when a user is trying to access an asset that either does not exist or has been moved. This commonly occurs when a permalink has been modified and no 301 redirect was put in place to redirect the user to the correct URL. There are a multiple variations of the 404 error which you might see dependent upon which server you are using. A few examples include:

  • 404 Not Found
  • Page Does Not Exist
  • 404 Not Found Nginx
  • Error 404
  • Not Found
  • HTTP Error 404

How to fix a 404 Not Found Nginx error

If you’re receiving a 404 Not Found Nginx error and have double checked that the asset(s) does in fact exist on your server, then there may be an issue with your configuration file. To check this, open your nginx.conf file and check if your site is using the correct path for the root folder. For example:

If the path is not correct, this could be the reason why your assets are returning a 404 Not Found Nginx error. Additionally, check the rewrite rules in your configuration file to ensure they aren’t misconfigured. A slight misconfiguration of a rewrite rule will change the URL to point to an incorrect path thus resulting in a Not Found error.

Tools to check for 404 Not Found errors

Apart from fixing internal 404 Not Found errors, you may also be linking to external resources that have been updated or removed. In this case, it is important to regularly perform 404 error checks to verify that your links aren’t broken. Regularly checking this and fixing any broken links will help ensure that you visitors’ user experience is not degraded by pointing them to a link that doesn’t work. A few tools you can use to check for 404 Not Found errors include the following:

    — This site allow you to simply enter your website URL and it will scan all of your pages looking for 404 Not Found errors as well as other errors. Once the scan is complete, it will return the results along with the URLs which appear to be broken.

— This Chrome extension is a simple extension that allows you to check the links of the current webpage you’re viewing. Once enabled, the extension will crawl the links on the page and will determine is they are valid or broken.

— This WordPress plugin provides users with many options for checking if your website has any broken links. A time period can be define that tells the plugin to check if existing links are broken every X hours. You can also define wether you want the plugin to send an email report of all broken links, choose which sections of your site to scan, etc.

If you’re experiencing a 404 Not Found Nginx error or rather just want to monitor your site to ensure none of the URLs have been modified, use the methods above to help ensure your website links remain accessible.

What does 404 error mean in Nginx

When your requests are handled successfully, the HTTP status code is not displayed on your browser. However, if anything goes wrong, your web browser will typically display a message with the HTTP status code to tell you the problem with the request. The error messages such as 504, 500, 503, 502, including the “Error 404 not found” message, are part of that process.

What does 404 error mean in Nginx

Essentially, the “404 error” indicates that your or your visitor’s web browser was connected successfully to the website server or the host. However, it was unable to locate the requested resource, such as filename or any specific URL.

For instance, If someone attempts to reach “yourwebsite.com/anypostname” and does not have any content linked with “anypostname“, in such a case, you will receive a 404 error on your browser as the resource requested does not exist. In other words, we can say that when a requested asset such as JavaScript, image, or CSS file is missing, your operational browser will generate a “404” error.

How to fix 404 error in Nginx

If you are getting a “404 Not Found” Nginx error and you have checked that the requested asset exists on your server, then your configuration file may be triggering the error. To fix the “404 Not Found”, open up your terminal by pressing “CTRL+ALT+T” and execute the below-given command for opening the Nginx configuration file:

Your Nginx configuration file will look like this:

If the path added in the Nginx configuration file is incorrect, it will result in a “404 Not Found” Ngnix error. So, verify your path leading towards the asset directory:

It will also be helpful to review your errors and access logs in Nginx. To do so, utilize the below-given “cat” command for extracting the content of the error_log present in the “/var/log/nginx/error.log” file:

To check the content of the access_log, write out this command in your terminal:

How to fix 404 Nginx error using online tools

The “404 Nginx error” is also linked with the external resources, and it occurs when those resources are removed or modified. That’s why it is crucial to run the 404 error checks frequently to ensure that your website links are not broken. A regular check-up and fixing the broken links will assist you in making sure that the user experience of your website visitor is at a stable level. The following are some of the tools that you can utilize for checking the “404 Not Found” errors:

W3C Check Link

In the W3C Link Checker online tool, you have to enter your website URL, and it will scan all of your web pages for 404 Not Found and other issues. When the scan is over, it will return all of the broken URLs along with other results:

Check My Links

Check My Links is a basic Chrome plugin that permits you to check the links on the current web page. When this plugin is activated, the extension will determine if the links on the current page are valid or broken:

Broken Link Checker

Broken Link Checker is another useful plugin that offers various methods for checking the broken links of your website. A time period can be set that instructs this plugin to check for broken links every “X” hour. You can choose whether the plugin should send an email report comprising all of the broken links or the site portion which is successfully scanned:

If you face a “404 Not Found” Nginx error or want to ensure that your website links are not broken or monitor your site, then utilize the above methods to fix it.

Conclusion

The “404 Not Found Error” on the web page is an HTTP response status code that declares your requested resource was not found. It can be difficult for you to figure out the reason behind the “404 not Found Error“. In this post, we have explained what the “404 Not Found Error” is. We also provided you the methods to fix the “404 Not Found Error” by utilizing the Nginx configuration file and the other online tools such as Check My Links, W3C Check Link, and the Broken Link Checker.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.

How to Fix Common Nginx Web Server Errors

Nginx is a very popular web server these days. This article will show you some common errors when running an Nginx web server and possible solutions. This is not a complete list. If you still can’t fix the error after trying the advised solutions, please check your Nginx server logs under /var/log/nginx/ directory and search on Google to debug the problem.

Unable to connect/Refused to Connect

If you see the following error when trying to access your website:

Firefox Unable to connect

It could be that

  1. Nginx isn’t running. You can check Nginx status with sudo systemctl status nginx . Start Nginx with sudo systemctl start nginx . If Nginx fails to start, run sudo nginx -t to find if there is anything wrong with your configuration file. And check the journal ( sudo journalctl -eu nginx ) to find out why it fails to start.
  2. Firewall blocking ports 80 and 443. If you use the UFW firewall on Debian/Ubuntu, run sudo ufw allow 80,443/tcp to open TCP ports 80 and 443. If you use Firewalld on RHEL/CentOS/Rocky Linux/AlmaLinux, run sudo firewall-cmd —permanent —add-service= , then sudo systemctl reload firewalld to open TCP ports 80 and 443.
  3. Fail2ban. If your server uses fail2ban to block malicious requests, it could be that fail2ban banned your IP address. Run sudo journalctl -eu fail2ban to check if your IP address is banned. You can add your IP address to the fail2ban ignoreip list, so it won’t be banned again.
  4. Nginx isn’t listening on the right network interface. For example, Nginx isn’t listening on the server’s public IP address.

If systemctl status nginx shows Nginx is running, but sudo ss -lnpt | grep nginx shows Nginx is not listening on TCP port 80/443, it could be that you deleted the following lines in the /etc/nginx/nginx.conf file.

So Nginx doesn’t use the virtual host files in /etc/nginx/conf.d/ directory. Add this line back.

nginx include virtual hosts file

The Connection Has Timed Out

the connection has timed out

This could mean that your server is offline, or Nginx isn’t working properly. I once had an out-of-memory problem, which caused Nginx to fail to spawn the worker processes. If you can see the following error message in /var/log/nginx/error.log file, your server is short of memory.

404 Not Found

nginx 404 not found

404 not found means Nginx can’t find the resources your web browser asks for. The reason could be:

  1. The web root directory doesn’t exist on your server. In Nginx, the web roor directory is configured using the root directive, like this: root /usr/share/nginx/linuxbabe.com/; . Make sure your website files (HTML, CSS, JavaScript, PHP) are stored in the correct directory.
  2. PHP-FPM isn’t running. You can check PHP-FPM status with sudo systemctl status php7.4-fpm (Debian/Ubuntu) or sudo systemctl status php-fpm .
  3. You forgot to include the try_files $uri /index.php$is_args$args; directive in your Nginx server config file. This directive is needed to process PHP code.
  4. Your server has no free disk space. Try to free up some disk space. You can use the ncdu utility ( sudo apt install ncdu or sudo dnf install ncdu ) to find out which directories are taking up huge amount of disk space.

403 Forbidden

This error means that you are not allowed to access the request resources. Possible scenario includes:

  • The website administrator blocks public access to the requested resources with an IP whitelist or other methods.
  • The website could be using a web application firewall like ModSecurity, which detected an intrusion attack, so it blocked the request.

Some web applications may show a different error message when 403 forbidden happens. It might tell you that “secure connection failed”, while the cause is the same.

secure connection failed nginx

500 Internal Server Error

Nginx 500 internal server error

This means there is some error in the web application. It could be that

  1. The database server is down. Check MySQL/MariaDB status with sudo systemctl status mysql . Start it with sudo systemctl start mysql . Run sudo journalctl -eu mysql to find out why it fails to start. MySQL/MariaDB process could be killed due to out-of-memory issue.
  2. You didn’t configure Nginx to use PHP-FPM, so Nginx doesn’t know how to execute PHP code.
  3. If your web application has a built-in cache, you can try flushing the app cache to fix this error.
  4. Your web application may produce its own error log. Check this log file to debug this error.
  5. Your web application may have a debugging mode. Turn it on and you will see more detailed error messages on the web page. For example, you can turn on debugging mode in the Modoboa mail server hosting platform by setting DEBUG = True in the /srv/modoboa/instance/instance/settings.py file.
  6. PHP-FPM could be overloaded. Check your PHP-FPM log (such as /var/log/php7.4-fpm.log ). If you can find the [pool www] seems busy (you may need to increase pm.start_servers, or pm.min/max_spare_servers) warning message, you need to allocate more resources to PHP-FPM.
  7. Sometimes reloading PHP-FPM ( sudo systemctl reload php7.4-fpm ) can fix the error.
  8. It also might be that you didn’t install the database module for PHP, so PHP can’t connect to the database. For MySQL/MariaDB, install it with sudo apt install php7.4-mysql . For PostgreSQL, install it with sudo apt install php7.4-pgsql .

Nginx Shows the default page

welcome to Nginx

If you try to set up an Nginx virtual host and when you type the domain name in your web browser, the default Nginx page shows up, it might be

  • Your Nginx virtual host file doesn’t have the server_name directive.
  • You didn’t use a real domain name for the server_name directive in your Nginx virtual host.
  • You forgot to reload Nginx.
  • You can try deleting the default virtual host file in Nginx ( sudo rm /etc/nginx/sites-enabled/default ).

The page isn’t redirecting properly

Firefox displays this error as The page isn’t redirecting properly . Google Chrome shows this error as www.example.com redirected you too many times .

Firefox The page isn’t redirecting properly

This means you have configured Nginx redirection too many times. For example, you may have added an unnecessary return 301 directive in the https server block to redirect HTTP to HTTPS connection.

If you have set up a page cache such as Nginx FastCGI cache, you need to clear your server page cache.

504 Gateway time-out

This means the upstream like PHP-FPM/MySQL/MariaDB isn’t able to process the request fast enough. You can try restarting PHP-FPM to fix the error temporarily, but it’s better to start tuning PHP-FPM/MySQL/MariaDB for faster performance.

Optimize MySQL/MariaDB Performance

Here is the InnoDB configuration in my /etc/mysql/mariadb.conf.d/50-server.cnf file. This is a very simple performance tunning.

  • The InnoDB buffer pool size needs to be at least half of your RAM. ( For VPS with small amount of RAM, I recommend setting the buffer pool size to a smaller value, like 400M, or your VPS would run out of RAM.)
  • InnoDB log file size needs to be 25% of the buffer pool size.
  • Set the read IO threads and write IO thread to the maximum (64) and
  • Make MariaDB use 3 instances of InnoDB buffer pool. The number of instances needs to be the same number of CPU cores on your system.

After saving the changes, restart MariaDB.

Find Out Which PHP Script Caused 504 Error

You can check the web server access log to see if there are any bad requests. For example, some folks might find the following lines in the Nextcloud access log file ( /var/log/nginx/nextcloud.access ).

Notice the HTTP status code 499, which means the HTTP client quit the connection before the server gives back an answer. Successful HTTP code should be 2xx or 3xx . If you can find HTTP code 4xx , it means there’s a problem with this HTTP request. In this example, the Nextcloud richdocumentscode app isn’t working.

Increase Timeout Settings

You can also set a longer timeout value in Nginx to reduce the chance of gateway timeout. Edit your Nginx virtual host file and add the following lines in the server <. >block.

If you use Nginx with PHP-FPM, then set the fastcgi_read_timeout to a bigger value like 300 seconds. Default is 60 seconds.

Then reload Nginx.

PHP-FPM also has a max execution time for each script. Edit the php.ini file.

You can increase the value to 300 seconds.

Then restart PHP-FPM

Memory Size Exhausted

If you see the following line in your Nginx error log, it means PHP reached the 128MB memory limit.

You can edit the php.ini file ( /etc/php/7.4/fpm/php.ini ) and increase the PHP memory limit.

Then restart PHP7.4-FPM.

If the error still exists, it’s likely there’s bad PHP code in your web application that eats lots of RAM.

PR_END_OF_FILE_ERROR

  1. You configured Nginx to rediect HTTP request to HTTPS, but there’s no server block in Nginx serving HTTPS request.
  2. Maybe Nginx isn’t running?
  3. Sometimes, the main Nginx binary is running, but a worker process can fail and exit due to various reasons. Check the Nginx error log ( /var/log/nginx/error.log ) to debug.

PHP-FPM Upstream Time Out

Some folks can find the following error in Nginx error log file ( under /var/log/nginx/ ).

  1. Restart PHP-FPM.
  2. Upgrade RAM. . Because PHP-FPM needs to fetch data from the database, if the database is slow to process requests, PHP-FPM will time out.

502 Bad Gateway

nginx 502 bad gateway

This error could be caused by:

  • PHP-FPM isn’t running. Check its status: sudo systemctl status php7.4-fpm .
  • PHP-FPM is running, but Nginx isn’t able to connect to PHP-FPM (Resource temporarily unavailable), see how to fix this error below.
  • PHP-FPM is running, but Nginx doesn’t have permission to connect to PHP-FPM socket (Permission denied). It might be that Nginx is running as nginx user, but the socket file /run/php/php7.4-fpm.sock is owned by the www-data user. You should configure Nginx to run as the www-data user.

Resource temporarily unavailable

Some folks can find the following error in Nginx error log file ( under /var/log/nginx/ ).

This usually means your website has lots of visitors and PHP-FPM is unable to process the huge amounts of requests. You can adjust the number of PHP-FPM child process, so it can process more requests.

Edit your PHP-FPM www.conf file. (The file path varies depending on your Linux distribution.)

The default child process config is as follows:

The above configuration means

  • PHP-FPM dynamically create child processes. No fixed number of child processes.
  • It creates at most 5 child processes.
  • Start 2 child processes when PHP-FPM starts.
  • There’s at least 1 idle process.
  • There’s at most 3 idle processes.

The defaults are based on a server without much resources, like a server with only 1GB RAM. If you have a high traffic website, you probably want to increase the number of child processes, so it can serve more requests. (Make sure you have enough RAM to run more child processes.)

Save and close the file. Then we also increase the PHP memory limit.

Find the following line.

By default, a script can use at most 128M memory. It’s recommended to set this number to at lest 512M.

Save and close the file. Restart PHP-FPM. (You might need to change the version number.)

To monitor the health of PHP-FPM, you can enable the status page. Find the following line in the PHP-FPM www.conf file.

Remove the semicolon to enable PHP-FPM status page. Then restart PHP-FPM.

Then edit your Nginx virtual host file. Add the following lines. The allow and deny directives are used to restrict access. Only the whitelisted IP addresses can access the status page.

Save and close the file. Then test Nginx configurations.

If the test is successful, reload Nginx for the changes to take effect.

Sample PHP-FPM status page.

Nginx PHP-FPM status page

The PHP-FPM www.conf file gives you a good explanation of what each parameter means.

PHP-FPM status page slow requests

If PHP-FPM is very busy and unable to serve a request immediately, it will queue this request. By default, there can be at most 511 pending requests, determined by the listen.backlog parameter.

If you see the following value on the PHP-FPM status page, it means there has never been a request put in the queue, i.e. your PHP-FPM can process requests quickly.

If there are 511 pending requests in the queue, it means your PHP-FPM is very busy, so you should increase the number of child processes.

You may also need to change the Linux kernel net.core.somaxconn setting, which defines max number of connections allowed to a socket file on Linux, such as the PHP-FPM Unix socket file. By default, its value is 128 before kernel 5.4 and 4096 starting with kernel 5.4.

If you run a high traffic website, you can use a big value. Edit /etc/sysctl.conf file.

Add the following two lines.

Save and close the file. Then apply the settings.

Note: If your server has enough RAM, you can allocate a fixed number of child processes for PHP-FPM like below. In my experience, this fixed the 500 internal error for a Joomla + Virtuemart website.

Two Virtual Host files For the Same Website

If you run sudo nginx -t and see the following warning.

It means there are two virtual host files that contain the same server_name configuration. Don’t create two virtual host files for one website.

PHP-FPM Connection reset by peer

Nginx error log file shows the following message.

This may be caused by a restart of PHP-FPM. If it’s retarted manually by yourself, then you can ignore this error.

Nginx Socket Leaks

If you find the following error message in the /var/log/nginx/error.log file, your Nginx has a socket leaks problem.

You can restart the OS to solve this problem. If it doesn’t work, you need to compile a debug version of Nginx, which will show you debug info in the log.

invalid PID number “” in “/run/nginx.pid”

You need to restart your web server.

Cloudflare Errors

Here are some common errors and solutions if your website runs behind Cloudflare CDN (Content Delivery Network).

521 Web Server is Down

  • Nginx isn’t running.
  • You didn’t open TCP ports 80 and 443 in the firewall.
  • You changed the server IP address, but forgot to update DNS record in Cloudflare.

The page isn’t redirecting properly

If your SSL setting on the SSL/TLS app is set to Flexible , but your origin server is configured to redirect HTTP requests to HTTPS, Your Nginx server sends reponse back to Cloudflare in encrypted connection. Since Cloudflare is expecting HTTP traffic, it keeps resending the same request, resulting in a redirect loop. In this case, you need to use the Full (strict) SSL/TLS option in your Cloudflare settings.

Cloudflare SSL TLS full strict

Wrapping Up

I hope this article helped you to fix common Nginx web server errors. As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks ��

Что означает ошибка 404 в Nginx?

Что означает ошибка 404 в Nginx

Изучение

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

Когда ваши запросы обрабатываются успешно, код состояния HTTP не отображается в вашем браузере. Однако, если что-то пойдет не так, ваш веб-браузер обычно отображает сообщение с кодом состояния HTTP, чтобы сообщить вам о проблеме с запросом. Сообщения об ошибках, такие как 504, 500, 503, 502, включая сообщение » Ошибка 404 не найдена «, являются частью этого процесса.

Что означает ошибка 404 в Nginx

По сути, » ошибка 404 ″ означает, что ваш веб-браузер или веб-браузер вашего посетителя был успешно подключен к серверу веб-сайта или хосту. Однако ему не удалось найти запрошенный ресурс, например имя файла или какой-либо конкретный URL-адрес.

Например, если кто-то попытается перейти на » yourwebsite.com/anypostname » и не имеет никакого контента, связанного с » anypostname «, в таком случае вы получите ошибку 404 в своем браузере, поскольку запрошенный ресурс не существует. Другими словами, мы можем сказать, что когда запрашиваемый ресурс, такой как файл JavaScript, изображение или CSS, отсутствует, ваш работающий браузер выдаст ошибку „404“.

Как исправить ошибку 404 в Nginx

Если вы получаете сообщение об ошибке Nginx » 404 Not Found » и проверили, что запрошенный актив существует на вашем сервере, то ваш файл конфигурации может вызывать ошибку. Чтобы исправить ошибку » 404 Not Found «, откройте свой терминал, нажав » CTRL + ALT + T «, и выполните приведенную ниже команду для открытия файла конфигурации Nginx:

Ваш файл конфигурации Nginx будет выглядеть так:

Ваш файл конфигурации Nginx будет выглядеть так

Если путь, добавленный в файл конфигурации Nginx, неверен, это приведет к ошибке Ngnix » 404 Not Found «. Итак, проверьте свой путь, ведущий к каталогу активов:

Также будет полезно просмотреть ваши ошибки и получить доступ к журналам в Nginx

Также будет полезно просмотреть ваши ошибки и получить доступ к журналам в Nginx. Для этого используйте приведенную ниже команду » cat » для извлечения содержимого error_log, присутствующего в файле » /var/log/nginx/error.log «:

Чтобы проверить содержимое access_log

Чтобы проверить содержимое access_log

Чтобы проверить содержимое access_log, запишите эту команду в своем терминале:

Как исправить ошибку 404 Nginx с помощью

Как исправить ошибку 404 Nginx с помощью онлайн-инструментов

» Ошибка 404 Nginx » также связана с внешними ресурсами и возникает, когда эти ресурсы удаляются или изменяются. Вот почему так важно часто выполнять проверку ошибок 404, чтобы убедиться, что ссылки на ваш веб-сайт не повреждены. Регулярная проверка и исправление неработающих ссылок поможет вам убедиться, что пользовательский опыт посетителя вашего веб-сайта находится на стабильном уровне. Ниже приведены некоторые инструменты, которые можно использовать для проверки ошибок «404 Not Found»:

W3C Проверить ссылку

В онлайн-инструменте W3C Link Checker вы должны ввести URL-адрес своего веб-сайта, и он просканирует все ваши веб-страницы на предмет 404 Not Found и других проблем. Когда сканирование закончится, оно вернет все неработающие URL-адреса вместе с другими результатами:

В онлайн-инструменте W3C Link Checker вы должны

Check My Links

Check My Links — это базовый плагин Chrome, который позволяет вам проверять ссылки на текущей веб-странице. Когда этот плагин активирован, расширение определит, действительны ли ссылки на текущей странице или нет:

действительны ли ссылки на текущей странице или нет

Broken Link Checker

Broken Link Checker — еще один полезный плагин, который предлагает различные методы проверки неработающих ссылок на вашем сайте. Можно установить период времени, при котором этот плагин будет проверять неработающие ссылки каждые «X» часов. Вы можете выбрать, должен ли плагин отправлять по электронной почте отчет, содержащий все неработающие ссылки или часть сайта, которая успешно просканирована:

неработающие ссылки или часть сайта, которая успешно просканирована

Если вы столкнулись с ошибкой Nginx «404 Not Found» или хотите убедиться, что ссылки на ваш сайт не сломаны, или отслеживать ваш сайт, используйте вышеуказанные методы, чтобы исправить это.

Заключение

» Ошибка 404 Not Found » на веб-странице — это код состояния HTTP-ответа, который объявляет, что запрошенный ресурс не найден. Вам может быть сложно выяснить причину » ошибки 404 not found «. В этом посте мы объяснили, что такое «ошибка 404 Not Found». Мы также предоставили вам способы исправить «ошибку 404 Not Found», используя файл конфигурации Nginx и другие онлайн-инструменты, такие как «Проверить мои ссылки», «Проверить ссылку W3C» и «Проверка неработающих ссылок».

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *