Ошибка 404 linux

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

В этой статье рассмотрим, почему возникает ошибка «404 not found Nginx», а также способы её устранения и отладки.Мы не будем разбираться с ситуацией, когда файла действительно нет на сервере — это решение, не требующее пояснений. Мы рассмотрим проблему обработки location в Nginx.

Давайте сначала разберёмся, как обрабатываются URL в Nginx. Когда веб-сервер определил, к какому блоку server (сайту) нужно передать запрос пользователя, просматриваются все префиксные блоки location и выбирается тот, который подходит лучше всего. Например, рассмотрим стандартную конфигурацию для WordPress. Здесь префиксные location отмечены зелёным, а с регулярным выражением — оранжевым:

location / {
index index.html index.php;
}
location /favicon.ico {
access_log off;
}
location ~* \.(gif|jpg|png)$ {
expires 30d;
}
location ~ \.php$ {
fastcgi_pass localhost:9000;
fastcgi_param SCRIPT_FILENAME
$document_root$fastcgi_script_name;
include fastcgi_params;
}

Префиксные локейшены всегда начинаются с символа /. Регулярные же содержат символы регулярных выражений: ~ $ ^ * и так далее. Если пользователь запрашивает favicon.ico, то будет выбран второй location, так как он лучше всего соответствует запросу, при любом другом запросе будет выбран location /, так как он соответствует всем запросам, а других префиксных location у нас нет. Это просто, а дальше начинается магия. После того, как был найден нужный location, Nginx начинает проверять все регулярные выражения в порядке их следования в конфигурационном файле.

При первом же совпадении Nginx останавливает поиск и передаёт управление этому location. Или, если совпадений не было найдено, используется ранее обнаруженный префиксный location. Например, если запрос заканчивается на .php, то первый location будет проигнорирован, а управление передастся четвёртому (~ \.php$)

Таким образом, любое неверно составленное регулярное выражение в любой части конфигурационного файла может полностью всё сломать. Поэтому разработчики рекомендуют по минимум использовать регулярные выражения. Что касается вложенных location, то обрабатываются они так же как и основные, только уже после передачи управления в нужный location. Путём чтения конфигурационного файла понять, какой location вызывает 404 сложно, поэтому, чтобы исправить ошибку, нам понадобиться режим отладки Nginx.

Как включить режим отладки Nginx?

Сначала нам необходимо установить версию Nginx с поддержкой отладки. Чтобы проверить, поддерживает ли ваша текущая версия этот режим, наберите:

nginx -V

В выводе должна быть строчка «—with-debug». Если её нет, значит отладка не поддерживается, и надо установить версию с поддержкой. В CentOS такой пакет называется nginx-debug. Для его установки наберите:

sudo yum install nginx-debug

Теперь появился ещё один исполняемый файл, и он собран уже с поддержкой отладки:

nginx-debug -V

Откройте конфигурационный файл вашего сайта или глобальный конфигурационный файл, если вы не задавали настройки логов отдельно для каждого сайта, и в конце стоки error_log замените error на debug:

error_log /var/log/nginx/domains/test.losst.pro.error.log debug

Останавливаем обычную версию и запускаем версию с отладкой:

systemctl stop nginx
systemctl start nginx-debug

Как исправить «404 Not Found Nginx»?

1. Регулярные выражения

Как я уже сказал выше, самой частой проблемой, которая вызывает 404, являются регулярные выражения. Смотрим, что происходит в лог файле:

tail -f /var/log/nginx/domains/test.losst.pro.error.log

Видим, что серверу пришёл запрос /vstats. Дальше он проверяет location: /, /robots.txt, /vatsts/, /site-control/. Здесь уже можем понять, в чём проблема — промазали на один слеш. Дальше проверяются все регулярные выражения, и, так как в них ничего найдено не было, выбирается location /.

Далее директива try_files пытается найти файл /vstats, не находит и ищет index.php, который, в свою очередь, возвращает 404.

Если мы наберём, то что ожидает видеть Nginx — /vstats/, то откроется наша страница статистики.

Если мы добавим к конфигурационному файлу ещё один location с регулярным выражением, например:

location ~* {
try_files $uri $uri/ =404;
}

То абсолютно все запросы будут обрабатываться именно этим регулярным выражением и, естественно, что ничего работать не будет. Видим, что приходит запрос /vstats/:

Он совпадает с префиксным location, но потом Nginx видит наше регулярное выражение и передаёт управление ему.

Поэтому будьте очень осторожны с регулярными выражениями, если они вам нужны, то размещайте их только внутри префиксных location, чтобы ограничить их область действия этим location, иначе может возникнуть ошибка 404 nginx.

2. Недостаточно памяти

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

Решить такую проблему можно, освободив память на сервере, часто такое может возникать из-за утечек памяти в php, когда процессы php-fpm занимают почти всю память на сервере. Поэтому перезапуск php-fpm решает проблему:

systemctl restart php-fpm

Чтобы избежать этой проблемы в будущем, можно настроить автоматический перезапуск процессов после обработки определённого количества запросов. Например каждые 200 запросов:

vi /etc/php-fpm.d/www.conf

pm.max_requests = 200

3. Не найден index

Если вы запрашиваете URL вида /vstats/, но в настройках Nginx не указан файл index, который нужно использовать для этой ссылки, то у вас ничего не выйдет, и вы получите 404. Вы можете добавить директиву index в ваш location:

location / {
index index.php index.html index.htm;
}

Или сразу в server, в Nginx все location наследуют директивы, установленные в server.

4. Другие проблемы

Подобных проблем, вызывающих 404 в Nginx, может быть очень много, но все они решаемы, и всё, что нужно для их решения, есть в отладочном логе Nginx. Просто анализируйте лог и на основе этого вносите исправления.

Выводы

В этой статье мы рассмотрели основные причины, из-за которых может возникнуть ошибка 404 not found Nginx. Как видите, может быть много проблем, но всё достаточно просто решается. А с какими проблемами, вызывающими эту ошибку, вы сталкивались? Как их решали? Напишите в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

When you visit an Nginx-configured website, your browser sends a request to the web server. After that, your web server responds with the data having an HTTP header. HTTP status codes are included in that HTTP header to explain how the request is responded.

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.

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:

$ sudo nano /etc/nginx/nginx.conf

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:

root /usr/share/nginx/html;

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:

$ sudo cat /var/log/nginx/error.log

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

$ sudo cat /var/log/nginx/access.log

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

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.

Ubuntu 14

When you’re running a website on an Nginx web server, encountering a 404 Not Found error can be frustrating. This error typically means that while the server itself is reachable, the specific page you’re trying to access isn’t. In this article, we’ll guide you through some troubleshooting steps to resolve this issue.

To troubleshoot a 404 Not Found error on an Nginx web server, you should first check the Nginx configuration to ensure that the server block is properly set up with the correct root directory and index file. Next, verify the file permissions and make sure they are readable by the Nginx user. If your website uses HTTPS, check the SSL configuration as well. Restart Nginx after making any changes. If the issue persists, check the Nginx error log for more specific information.

  1. Understanding the 404 Error
  2. Check the Nginx Configuration
    • Verify Server Block Configuration
    • Check File Permissions
    • Check the SSL Configuration
  3. Restart Nginx
  4. Check the Nginx Error Log
  5. Conclusion

Understanding the 404 Error

The 404 Not Found error is an HTTP status code that means the server couldn’t find the requested resource. In the context of a web server like Nginx, this usually means that there’s no match for the URL you’re trying to access in the server’s configuration or the file doesn’t exist in the site’s root directory.

Check the Nginx Configuration

The first step in troubleshooting is to check your Nginx configuration. The configuration files for Nginx are typically located in the /etc/nginx/ directory.

Verify Server Block Configuration

The server block (also known as a virtual host) configurations are located in the /etc/nginx/sites-available/ directory. Each website hosted on your server should have its own configuration file here.

Here’s an example of what a server block might look like:

server {
 listen 80;
 server_name test.com www.test.com;
 root /var/www/test.com/html;
 index index.html index.htm;
}

In this example, listen 80; is telling Nginx to listen on port 80, which is the standard HTTP port. The server_name directive should be set to your website’s domain name. The root directive specifies the root directory of your website, where your index file is located. The index directive lists the names of files that Nginx should try to serve as the default page if a specific one isn’t requested.

Make sure that the root directive points to the correct directory and that an index file exists there.

Check File Permissions

Next, check the permissions of the files and directories of your website. They should be readable by the user that Nginx runs as, which is usually www-data.

You can check the current permissions with the ls -l command:

ls -l /var/www/test.com/html

The output will show the permissions, owner, group, and name of the files and directories in the specified directory. The permissions are displayed in the form rwxrwxrwx, which represents the permissions for the owner, group, and others, respectively. The r stands for read, w for write, and x for execute.

If the permissions are incorrect, you can change them with the chmod command, and you can change the owner with the chown command:

sudo chown -R www-data:www-data /var/www/test.com/html
sudo chmod -R 755 /var/www/test.com/html

In the chown command, -R means to apply the change recursively to the directory and its contents. www-data:www-data is the user and group that you’re changing the owner to.

In the chmod command, 755 sets the permissions to read, write, and execute for the owner, and read and execute for the group and others.

Check the SSL Configuration

If your website uses HTTPS, you also need to check the SSL configuration in the Nginx server block. It should look something like this:

server {
 listen 443 ssl;
 server_name test.com www.test.com;
 root /var/www/test.com/html;
 index index.html index.htm;

 ssl_certificate /etc/letsencrypt/live/test.com/fullchain.pem;
 ssl_certificate_key /etc/letsencrypt/live/test.com/privkey.pem;
}

The listen 443 ssl; directive tells Nginx to listen on port 443, which is the standard HTTPS port, and to enable SSL. The ssl_certificate and ssl_certificate_key directives specify the locations of the SSL certificate and private key files, respectively.

Make sure that the paths to the SSL certificate and private key files are correct and that the files are readable by the www-data user.

Restart Nginx

After making any changes to the Nginx configuration, you need to restart the service for the changes to take effect. You can do this with the following command:

sudo service nginx restart

Check the Nginx Error Log

If you’re still encountering the 404 error after following the above steps, the next place to look is the Nginx error log. By default, it’s located at /var/log/nginx/error.log.

You can view the most recent entries in the log with the tail command:

sudo tail /var/log/nginx/error.log

The error log can provide more specific information about what’s causing the 404 error.

Conclusion

Troubleshooting a 404 Not Found error on an Nginx web server involves checking the server block configuration, file permissions, and SSL configuration, and examining the Nginx error log. By following these steps, you should be able to identify and resolve the issue.

If you encounter a 404 Not Found error on your Nginx web server, you should first check your Nginx configuration. Verify the server block configuration to ensure that the root directory and index file are correctly specified. Also, check the file permissions to ensure that they are readable by the Nginx user (www-data). If your website uses HTTPS, make sure to check the SSL configuration as well. After making any changes to the configuration, restart Nginx for the changes to take effect. If the issue persists, check the Nginx error log for more specific information about the error.

The Nginx configuration files are typically located in the /etc/nginx/ directory. The server block configurations for each website hosted on your server can be found in the /etc/nginx/sites-available/ directory.

Nginx returns an HTTP
404 NOT FOUND error when it cannot find the requested resource. How should you handle Nginx
404 Not Found errors?

How to fix an HTTP 404 error in Nginx?

To be able to fix an HTTP 404 error in Nginx it is important to look at the Nginx error log:

[error] 31#31: *1 "/etc/nginx/html/index.html" is not found (2: No such file or directory), client: 172.17.0.1, server: , request: "GET / HTTP/1.1", host: "localhost:8080"

Check the path to the file. If it doesn’t exist, either move the files to that directory or
change your Nginx config to point to the right directory.

But if the file exists, it might be that one of the following issues causes a 404 error:

  1. Incorrect file permissions
  2. Filename case sensitivity
  3. Wrong root directory in nginx.conf
  4. No matching location directive in nginx.conf
  5. You use root instead of alias (or vice-versa)

Incorrect file permissions

Nginx returns a 404 error if it has no permission to read the requested file. If the files
are stored in
/etc/nginx/html/mywebsite, check that Nginx user (usually you name
this user www-data or nginx) has read
permissions.

ls -l /etc/nginx/html/mywebsite

To check if the Nginx user can access one of your html files use:

su <nginx-user> -s /bin/bash -c 'if [ -r <path-to-html-file> ]; then echo "Readable"; else echo "Invalid permissions"; fi'

Depending on your situation, change ownership of the files or adjust the permissions such
that the Nginx user has permission to read the file.

Filename case sensitivity

An easy to overlook issue is case sensitivity. Double check your filenames if they have the
correct casing!

Wrong root directory in nginx.conf

A simple Nginx configuration file might look like this:

/etc/nginx/nginx.conf

events {
    worker_connections  1024;
}

http {
    index index.html index.htm;

    server {
        listen       80;

        root /usr/share/nginx/html; # Pay attention to this

        location / {
        }
    }
}

The root directive tells Nginx in which directory it must look for files to serve to the
client. Make sure the directory exists and contains the files you want to serve.

No matching location directive in nginx.conf

Location directives specify configuration that applies when a URL matches a specific
pattern. This is used for example to match a context path or file extension. Let’s look at
an nginx.conf:

/etc/nginx/nginx.conf

events {
    worker_connections  1024;
}

http {
    index    index.html index.htm;

    server {
        listen       80;

        location /context-path {
            root /usr/share/nginx/html;
        }
    }
}

Suppose there is a file index.html in /usr/share/nginx/html. If you now request the https://[server-url]/index.html, you will
get a 404 Not Found error.

To fix this you can either:

  1. add a location directive or
  2. move the root directive from location to
    the
    server directive.

Use of root instead of alias (or vice-versa)

Suppose the files we want to serve are in /usr/share/nginx/html/. We
want to serve them at http:localhost:8080/context-path/.

In this case, you might want to use alias over root:

/etc/nginx/nginx.conf

events {
    worker_connections  1024;
}

http {
    index    index.html;

    server {
        listen       80;

        location /context-path {
            alias /usr/share/nginx/html/; # Don't use root here
        }
    }
}

The difference between alias and root is
that:

  1. root takes the full context-path (/context-path) and puts that after the root. Nginx will look for files in: /usr/share/nginx/html/context-path/
  2. alias takes the part after the location
    directive and puts that after the root. Nginx will look for files
    in: /usr/share/nginx/html/

How to prevent 404 Not Found for Nginx?

Test your website with a broken link checker. A broken link test that sends you
notifications can help detect 404 Not Found errors early.

Test your website now with the free broken link test:

Overview. Generally, the [Errno 14] HTTPS Error 404 — Not Found error is observed due to inconsistent metadata of the repositories or if the client could not find or access the requested package on the server.

What is error 404 in Linux?

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.

How do I fix error404?

4 Ways to Resolve 404 Errors

  1. Restart your browser. Try closing the current window and opening a new one. …
  2. Clear cache. Remove your browser data and history. …
  3. Double-check for mistyped characters. …
  4. Use another device. …
  5. Switch to the Incognito window.

What is error 404 in apt get install?

The “404 Not Found” error occurs when you can run “apt update” or “apt-get update” command on the old Ubuntu terminal. This type of error occurs because the PPA repository you added in the Ubuntu repository list isn’t compatible and as a result it fails to update on your system.

What is the reason for 404 error?

The typical trigger for an error 404 message is when website content has been removed or moved to another URL. There are also other reasons why an error message could appear. These include: The URL or its content (such as files or images) was either deleted or moved (without adjusting any internal links accordingly)

Fixed! Error: 404 Not Found | Error: 404 not found[IP: 91.189.92.201 80] |apt-get update error

Does 404 error mean I was blocked?

404 errors: These occur when a page can’t be found. This can happen if the page has been deleted or if the URL has been typed incorrectly. 400 errors: These indicate that the server is unable to process the request. This can happen if the website is down for maintenance or if there is an error in the code.

What is the most common error 404?

HTTP Error 404 (Not Found)

A 404 error happens when you try to access a resource on a web server (usually a web page) that doesn’t exist. Some reasons for this happening can for example be a broken link, a mistyped URL, or that the webmaster has moved the requested page somewhere else (or deleted it).

How do I fix apt install error?

To fix broken packages on Debian-based distributions using APT:

  1. Open the terminal by pressing Ctrl + Alt + T on your keyboard and enter: sudo apt —fix-missing update.
  2. Update your system’s package list from the available sources: sudo apt update.
  3. Now, force the installation of the broken packages using the -f flag.

How to install apt in Linux?

Follow these steps to install APT on your RPM-based Linux distribution:

  1. As a preliminary step, update and upgrade your system using: sudo dnf upgrade.
  2. Issue the following command to install APT using the DNF package manager: sudo dnf install apt.

How to install apt update in Linux?

Follow these steps:

  1. Open up a terminal window.
  2. Issue the command sudo apt-get upgrade.
  3. Enter your user’s password.
  4. Look over the list of available updates (see Figure 2) and decide if you want to go through with the entire upgrade.
  5. To accept all updates click the ‘y’ key (no quotes) and hit Enter.

Why is apt command not working?

If you receive a ‘command not found’ message when trying to run an apt command such as apt-get or apt-cache , the first thing to consider is the Linux distribution you are using. Apt is a software package management tool for Debian or Debian-based Linux systems such as Ubuntu, Linux Mint, Kali Linux and Parrot OS.

How long does a 404 error last?

404 Code: When Google comes across a 404 code, it will continue to circulate the page through its index, because a 404 indicates that the page will eventually come back. If a page is still returning a 404 page after 6-12 months, a search engine will deindex it.

What is error 404 file or directory not found?

The Web server returns the HTTP 404 — File not found error message when it cannot retrieve the page that was requested. The following are some common causes of this error message: The requested file has been renamed. The requested file has been moved to another location and/or deleted.

What does a 404 mean?

The HTTP 404 Not Found response status code indicates that the server cannot find the requested resource. Links that lead to a 404 page are often called broken or dead links and can be subject to link rot. A 404 status code only indicates that the resource is missing: not whether the absence is temporary or permanent.

What is 404 error page address?

A 404 error page is a web page designated to be displayed when a request triggers the HTTP 404 response code. This code means the client (or, “visitor”) was able to locate the server, but not the specific destination. In other words, they found your site, but not a specific page within your site.

What is apt command in Linux?

The apt command is a powerful command-line tool, which works with Ubuntu’s Advanced Packaging Tool (APT). The commands contained within apt provide the means for installing new software packages, upgrading existing software packages, updating the package list index, and even upgrading the entire Ubuntu system.

What is the Linux apt-get command?

apt-get is a command line tool for interacting with the Advanced Package Tool (APT) library (a package management system for Linux distributions). It allows you to search for, install, manage, update, and remove software. The tool does not build software from the source code.

How do I know if apt is installed?

How do I see what packages are installed on Ubuntu Linux?

  1. Open the terminal application or log in to the remote server using ssh (e.g. ssh user@sever-name )
  2. Run command apt list —installed to list all installed packages on Ubuntu.

What can I use instead of apt?

Nala is a free, open source alternative front-end to apt (which itself is something of a front-end to dpkg ).

How do I manually update Linux?

Option A: Use the System Update Process

  1. Step 1: Check Your Current Kernel Version. At a terminal window, type: uname –sr. …
  2. Step 2: Update the Repositories. At a terminal, type: sudo apt-get update. …
  3. Step 3: Run the upgrade. While still in the terminal, type: sudo apt-get dist-upgrade.

How do I install apt in terminal?

When the package is directly available in default repositories, you can install it by running the “apt-get” command with the “install” option. Note : you will need sudo privileges in order to install new packages on your system. You may also be asked if you accept to install this package on your system.

How do I manually install apt packages?

You can do this in two separate steps:

  1. Install the package with dpkg . sudo dpkg -i packagename.deb.
  2. That created missing dependencies. apt-get can fix missing dependencies automatically. sudo apt-get -f install. That should also automatically finish configuring the original package.

What does sudo mean in Linux?

sudo , which is an acronym for superuser do or substitute user do, is a command that runs an elevated prompt without a need to change your identity.

How do I run an apt file?

apt-file is a command line tool for searching files in packages for the APT package management system. Some actions are required to run the search: find Alias for search. list List the contents of a package. This action is very close to the dpkg -L command except the package does not need to be installed or fetched.

How to refresh Linux from terminal?

Just hold down Ctrl + Alt + Esc and the desktop will be refreshed.

Понравилась статья? Поделить с друзьями:
  • Ошибка 403 тендер
  • Ошибка 404 json
  • Ошибка 404 и 405
  • Ошибка 404 на авито
  • Ошибка 404 автокад