Ошибка 500 внутренняя ошибка сервера nginx

При разработке веб-сайтов и веб-приложений можно столкнуться с ошибкой 500 internal server error. Сначала она может испугать и ввести в заблуждение, поскольку обычно веб-сервер выдает более конкретные ошибки, в которых указана точная причина проблемы, например, превышено время ожидания, неверный запрос или файл не найден, а тут просто сказано что, обнаружена внутренняя ошибка.

Но не все так страшно и в большинстве случаев проблема вполне решаема и очень быстро. В этой статье мы разберем как исправить ошибку Internal server error в Nginx.

Дословно Internal server error означает внутренняя ошибка сервера. И вызвать её могут несколько проблем. Вот основные из них:

  • Ошибки в скрипте на PHP — одна из самых частых причин;
  • Превышено время выполнения PHP скрипта или лимит памяти;
  • Неправильные права на файлы сайта;
  • Неверная конфигурация Nginx.

А теперь рассмотрим каждую из причин более подробно и разберем варианты решения.

1. Ошибка в скрипте PHP

Мы привыкли к тому, что если в PHP скрипте есть ошибки, то сразу же видим их в браузере. Однако на производственных серверах отображение сообщений об ошибках в PHP отключено, чтобы предотвратить распространение информации о конфигурации сервера для посторонних. Nginx не может отобразить реальную причину ошибки, потому что не знает что за ошибка произошла, а поэтому выдает универсальное сообщение 500 internal server error.

Чтобы исправить эту ошибку, нужно сначала понять где именно проблема. Вы можете включить отображение ошибок в конфигурационном файле php изменив значение строки display_errors с off на on. Рассмотрим на примере Ubuntu и PHP 7.2:

vi /etc/php/7.2/php.ini

display_errors = On

Перезапустите php-fpm:

sudo systemctl restart php-fpm

Затем обновите страницу и вы увидите сообщение об ошибке, из-за которого возникла проблема. Далее его можно исправить и отключить отображение ошибок, тогда все будет работать. Ещё можно посмотреть сообщения об ошибках PHP в логе ошибок Nginx. Обычно он находится по пути /var/log/nginx/error.log, но для виртуальных доменов может настраиваться отдельно. Например, смотрим последние 100 строк в логе:

tail -n 100 -f /var/log/nginx/error.log

Теперь аналогично, исправьте ошибку и страница будет загружаться нормально, без ошибки 500.

2. Превышено время выполнения или лимит памяти

Это продолжение предыдущего пункта, так тоже относится к ошибкам PHP, но так, как проблема встречается довольно часто я решил вынести её в отдельный пункт. В файле php.ini установлены ограничения на время выполнения скрипта и количество оперативной памяти, которую он может потребить. Если скрипт потребляет больше, интерпретатор PHP его убивает и возвращает сообщение об ошибке.

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

Если же отображение ошибок отключено, мы получаем error 500. Обратите внимание, что если время ожидания было ограничено в конфигурационном файле Nginx, то вы получите ошибку 504, а не HTTP ERROR 500, так что проблема именно в php.ini.

Чтобы решить проблему увеличьте значения параметров max_execution_time и memory_limit в php.ini:

sudo vi /etc/php/7.2/php.ini

max_execution_time 300
memory_limit 512M

Также проблема может быть вызвана превышением других лимитов установленных для скрипта php. Смотрите ошибки php, как описано в первом пункте. После внесения изменений в файл перезапустите php-fpm:

sudo systemctl restart php-fpm

3. Неверные права на файлы

Такая ошибка может возникать, если права на файлы, к которым обращается Nginx установлены на правильно. Сервисы Nginx и php-fpm должны быть запущены от имени одного и того же пользователя, а все файлы сайтов должны принадлежать этому же пользователю. Посмотреть от имени какого пользователя запущен Nginx можно командой:

nginx -T | grep user

Чтобы узнать от какого пользователя запущен php-fpm посмотрите содержимое конфигурационного файла используемого пула, например www.conf:

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

В моем случае это пользователь nginx. Теперь надо убедится, что файлы сайта, к которым вы пытаетесь обратиться принадлежат именно этому пользователю. Для этого используйте команду namei:

namei -l /var/www/site

Файлы сайта должны принадлежать пользователю, от имени которого запущены сервисы, а по пути к каталогу с файлами должен быть доступ на чтение для всех пользователей. Если файлы принадлежат не тому пользователю, то вы можете все очень просто исправить:

sudo chown nginx:nginx -R /var/www/site

Этой командой мы меняем владельца и группу всех файлов в папке на nginx:nginx. Добавить права на чтение для всех пользователей для каталога можно командой chmod. Например:

sudo chmod o+r /var/www/

Далее все должно работать. Также, проблемы с правами может вызывать SELinux. Настройте его правильно или отключите:

setenforce 0

Выводы

В этой статье мы разобрали что делать если на вашем сайте встретилась ошибка 500 internal server error nginx. Как видите проблема вполне решаема и в большинстве случаев вам помогут действия описанные в статье. А если не помогут, напишите свое решение в комментариях!

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

Creative Commons License

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

If you’ve ever encountered the 500 internal server error Nginx on your website, we know how frustrating and stressful it can be. You may have spent hours or even days creating and designing your website, and the thought of visitors being unable to access it can be disheartening.

But you do not need to worry, we’re here to help you to fix this Nginx server error with the best possible troubleshooting methods!

In this Guide, we’ll walk you through the main causes that trigger 500 internal server error Nginx, How to prevent it, and the steps to fix the Nginx 500 error and get your website back up and running.

500 Internal Server Error Message Nginx
500 Internal Server Error Message Nginx

Let us get started then!


Read: 🚩 How to fix HTTP 500 Internal Server Error in WordPress?


What does the 500 internal server error Nginx mean?

The 500 internal server error Nginx simply means that something has gone wrong on the server side of things. It is a generally comprehensive response that indicates the server could not able to determine the exact error code in response.

This could be due to a variety of factors, including faulty scripts, misconfigured servers, incompatible plugins, or inadequate file permissions.

Whatever the cause may be, the 500 Internal Server Error Nginx is a sign that something is preventing the server from functioning as it should.

One of the most common reasons for this error is an issue with one of the web servers that NGINX is working with, such as Apache. If the web server encounters an issue and returns a 500 error response to NGINX, this error message can then be returned to the client’s browser and displayed on the screen as 500 Internal Server Error Nginx.


What Are The Causes Of 500 Internal Server Errors Nginx?

The Nginx 500 Internal Server Error can be a real headache for website owners, causing frustration and anxiety. Below are some of the most common reasons that cause 500 internal server errors in Nginx.

  • Misconfigured Server
  • Incompatible Plugins
  • A faulty script
  • Inadequate File Permissions

1. A misconfigured server

A misconfigured server can lead to an error, causing a conflict between the server and the browser, leading to a disruption in the communication between the two. This can be due to server mismanagement, which can be caused by human error, a lack of expertise, or outdated software.

2. Incompatible plugins

Sometimes the WordPress plugins that you have installed can be the possible cause of the 500 internal server error Nginx. These plugins may have compatibility issues with the website, leading to the error. This can be due to plugin updates, which can cause compatibility issues with other plugins or website software.

3. A faulty script

A faulty script is another possible cause of the Nginx 500 Internal Server Error. Scripts can become corrupted, causing issues with the website’s functionality, and leading to the error. This can be due to programming errors, file corruption, or compatibility issues.

4. Inadequate file permissions

Insufficient file permissions can prevent the server from accessing or modifying files, leading to errors. This can be due to user error, misconfigured file permissions, or file corruption.

By understanding and identifying the root cause of the 500 Internal Server Error in Nginx, you can take the necessary steps to resolve the issue and ensure that the website runs smoothly and efficiently.


Let us check out them in detail.

1. Force Refresh or Reload your Webpage

The 500 Internal Server Error in Nginx can sometimes appear on your screen due to a temporary issue with your server. The server may be restarting or may be overburdened with too many requests to handle, resulting in insufficient resources to process them.

If it is the case, then Force refreshing or reloading the webpage can do the job. To do this,

  • Press the Windows + R key simultaneously or Press the F5 key in windows.
  • For Mac, Press Apple + R or Cmd+shift+ R key simultaneously
  • For Linux, Press F5 Key

2. Clear Browser Cookies and Cache memory

If the Nginx 500 internal server error is triggered due to a cache-related issue, clearing your browser’s cookies and cache memory can help. Here are the steps you can follow:


Note: Since Chrome has a major Browser market share, here we will be using Chrome for this tutorial.


Step 1: Depending on your browser, navigate to the settings menu. In Google Chrome, you can click on the three vertical dots in the upper right corner of the window.

Step 2: Select “More tools” and Click on “Clear browsing data“.

Clear browsing data on Chrome

Clear browsing data on Chrome

Step 3: A pop-up window will open on which, you can select all three options under the “Basic” section as shown in the picture below. These options are “Browsing history“, “Cookies and other site data“, and “Cached images and files“.

Step 4: Click on “Clear data” to initiate the process.

Clearing data in Google Chrome

Clearing data in Google Chrome

Quick tip: Alternatively you can try to access the website in Private or Incognito mode, in which the browser doesn’t store any cookies/cache of the website you visit.

3. Deactivate or Disable VPN

Sometimes, your Internet Service Provider (ISP) can be at fault. You can add a VPN or use a VPN client to access the website again.

However, if you have already used VPN, try to deactivate it and then access the website. To do this,

Press the Windows Key + I simultaneously to open the settings interface.

Go to the Network and Internet

Click on VPN, located on the right pane, select your VPN and click on the Remove button.

If you are using any VPN client, do not forget to disconnect it from the VPN.

Removing VPN from Windows PC
Removing VPN from Windows PC

After completing all the steps, restart your device and check whether the 500 internal server error in Nginx has been resolved or not.

4. Remove Unwanted Browser Extensions

If you have installed a lot of plugins or extensions on your browsers, try to delete or remove the unwanted ones. Sometimes, extensions can also create issues that can trigger such types of errors.

5. Check Server Logs

You can also check out your error logs and find out the possible causes that trigger 500 internal server errors Nginx. All you need to do is log in to the FTP client and then navigate to the Error log Directory and either download it or directly open it in an editor.

This will help you to narrow down the issue so that you easily figure out the exact problem and you can immediately fix it. 


You can also read our complete guide on How to access and set up WordPress error logs?


6. Check out the Scripts

  • Check Nginx error logs: The first step is to look at the error logs for Nginx, which are usually located in the /var/log/nginx/error.log file (or a similar location depending on your configuration). Look for any error messages related to the 500 error, such as “upstream timed out” or “connect() failed”.
  • Check PHP error logs: If you’re running PHP scripts, check the PHP error logs as well. These logs may provide more specific information about the cause of the error, such as syntax errors or runtime issues.
  • Check permissions: Make sure that the script and any files it accesses have the correct permissions. Check the owner and group of the script and files and make sure they match the user running the Nginx process.
  • Check syntax: If the script is written in a scripting language like PHP, make sure that the syntax is correct. You can do this by running the script from the command line and checking for any syntax errors.
  • Check for infinite loops: If the script is in a loop that never ends, it can cause Nginx to timeout and return a 500 error. Look for any infinite loops in the script and fix them.
  • Check resource limits: Check the resource limits for the server, such as the maximum memory or CPU usage. If the script is using too many resources, it can cause Nginx to timeout and return a 500 error. Increase the limits if necessary.
  • Check for database errors: If the script is accessing a database, check the database logs for any errors or connection issues.

Read: 🚩 How to Fix HTTP 504 Gateway Timeout Error?


7. Check whether adequate permission is granted to folders and files.

To make the WordPress website work perfectly fine, it is essential to have all the directory and file permissions correctly configured. The recommended file permission settings are as follows:

  • 755 for all folders and sub-folders.
  • 644 for all files.

Incorrect permission settings will lead to the blocking of some plugins, themes, and scripts to work. 

At WPOven you can use the “Fix Permissions” tool for fixing file permissions in Sites->Tools in the dashboard. 

8. Check all your redirections

Sometimes misconfigured or incorrect redirections in web servers can show 500 internal server error Nginx. Make sure to check that files like mod_rewrite or .htaccess are properly configured and working as they should be.

9. Increase Script timeout value

Sometimes, web servers take longer time than usual to send a request, and if the response time exceeds the timeout value, the web server may time out on the request without waiting for Nginx to respond. This can result in a 500 internal server error Nginx.

To avoid this situation, it is recommended that you increase your web server’s timeout value. This will give your server more time to connect with Nginx and receive a valid response.

10. Contact your Web hosting provider or Developer

If none of the above-mentioned methods can help you fix the 500 Internal Server Error Nginx, the last option left is to contact the support team of your web hosting provider or seek assistance from a developer for further help


Best Practices For Preventing 500 Internal Server Error Nginx

  • Regularly update server software and plugins
  • Monitor server logs
  • Use a content delivery network (CDN)
  • Optimize website performance and reduce resource usage
  • Use a backup system

Regular Update Server Software and plugins: Regularly updating server software and plugins with their latest version available is crucial to ensure that your website is running on the latest and most secure version of your server and plugins. Outdated software can be vulnerable to security threats, which can cause internal server errors.

Monitor server logs: Monitoring server logs is also important, as it can help you identify potential issues before they become major problems. Checking server logs regularly can help you detect unusual activity or errors, allowing you to take quick action before it causes an internal server error.

Use CDN: CDN or Content Delivery Network can help improve website performance and reduce server load, reducing the risk of internal server errors. CDNs help distribute website content across multiple servers, reducing the load on any single server and improving website speed.

Optimizing website performance and reducing resource usage: It is another important step in preventing internal server errors. This can involve techniques like image compression, minification of code, and reducing the number of HTTP requests.

Use a backup system: It is crucial for ensuring that your website can quickly recover from any internal server errors or other issues. Regular backups can help you restore your website to a previous version quickly and easily, reducing downtime and minimizing the impact of any errors or issues. Check out this dedicated blog on “How to Backup WordPress Site in 5 minutes“.


Conclusion

Tackling the 500 internal server error Nginx can be stressful and frustrating for any individual, but with the proper troubleshooting steps outlined that we have mentioned in this guide, you can easily figure out the issue and fix it.

In addition to that, also do not forget to implement the best practices that we have mentioned to prevent to prevent this error to happen in the future.

Always remember, a well-functioning website is essential for the success of your business, and we’re here to assist you in achieving that. If you have any queries or would like to add any valuable points to it, please do let us know in the comment section below.


Frequently Asked Questions

How do I fix NGINX 500 internal server error?

Here are some best troubleshooting methods you can try to fix 500 internal server errors Nginx on Ubuntu, PHP, WordPress, or other platforms.
1. Force Refresh or Reload your Webpage
2. Clear Browser Cookies and Cache memory
3. Deactivate or Disable VPN
4. Remove Unwanted Browser Extensions
5. Check Server Logs
6. Check out the Scripts
7. Check whether adequate permission is granted to folders and files.
8. Check all your redirections
9. Increase Script timeout value

What causes 500 internal server error?

Here are some of the most common issues due to which your WordPress website has an HTTP 500 Internal Server Error.
1. Corrupt .htaccess file
2. Exceeding PHP Memory Limit
3. Faulty Plugin or theme Issue
4. Corrupted Core Files
5. Check File Permissions
6. Unsupported PHP Version
7. Incorrect DNS entries
8. Problem with the Server itself
9. Inode Limitation Reached

Is a 500 error my fault?

If you are getting 500 internal server error Nginx message, it means there is something went wrong on the server side. There is nothing wrong, with the client side, i.e browser, your computer, or the internet connectivity. It is simply a problem with your website.


by Loredana Harsana

Loredana is a passionate writer with a keen interest in PC software and technology. She started off writing about mobile phones back when Samsung Galaxy S II was… read more


Updated on March 13, 2023

Fact checked by
Alex Serban

Alex Serban

After moving away from the corporate work-style, Alex has found rewards in a lifestyle of constant analysis, team coordination and pestering his colleagues. Holding an MCSA Windows Server… read more

  • The 500 Internal Server Error in NGINX is a common issue that prevents it from returning a proper response.
  • These errors mainly occur due to a faulty script or missing files referenced by code.
  • One of the recommendations includes clearing the browser’s cache data, so don’t hesitate to try the steps mentioned below.

500 internal server error NGINX

Strugling with your current browser? Upgrade to a better one: OperaYou deserve a better browser! 350 million people use Opera daily, a fully-fledged navigation experience that comes with various built-in packages, enhanced resource consumption and great design. Here’s what Opera can do:

  • Easy migration: use the Opera assistant to transfer exiting data, such as bookmarks, passwords, etc.
  • Optimize resource usage: your RAM memory is used more efficiently than in other browsers
  • Enhanced privacy: free and unlimited VPN integrated
  • No ads: built-in Ad Blocker speeds up loading of pages and protects against data-mining
  • Gaming friendly: Opera GX is the first and best browser for gaming
  • Download Opera

NGINX is an open-source software used for web serving, reverse proxying, caching, load balancing, etc. It started as a web server designed for maximum performance and stability.

The 500 Internal Server Error is a common issue that prevents it from returning a proper response. Errors like these can occur due to a faulty script or missing files referenced by code.

NGINX is typically a reverse proxy server, so one of the most common reasons for the 500 Internal Server Error could be one of its web servers like Apache.

Keep reading this post to know more about this error and how to fix it in no time.

What is the meaning of the 500 Internal Server Error?

The 500 Internal Server Response code indicates that the website has encountered an unexpected condition that is this evening it from fulfilling the request.

It’s a generic catch-all response that shows that the server cannot find a better error code in response. This error code is a very general HTTP status code on the website server but isn’t precisely the exact problem.

Quick Tip:

The Opera browser has a VPN proxy that allows you to connect to a few servers. Accessing Opera and connecting to a different server is helpful when you have internal server issues with another browser.

When you click on the blue VPN box, a drop-down menu appears, allowing you to switch the VPN on or off and pick a location.

Opera

With the built-in VPN, you can change the location and bypass internal server issues in NGINX.

What can I do to fix the 500 Internal Server Error in NGINX?

1. Reload the web page

This error can occur sometimes due to a temporary problem on the webserver. If that’s the case reloading the page might help.

Reload the page by pressing F5 or CTRL + R and check if the NGINX 500 Internal Server Error localhost message disappears.

2. Clear your browser’s cookies and cache

On Chrome

  1. Open Google Chrome and click on three vertical dots at the top right corner.
  2. Click on Settings and navigate to Privacy and Security.
  3. Click on Clear Browsing Data.
    500 internal server error NGINX
  4. Check the options Cookies and other site data and Cached images and files.
  5. Once done, click on Clear Data.
    500 internal server error NGINX

If Chrome’s cache data gets corrupt or full it can cause the 500 Internal Server Error NGINX. Clear Chrome’s cache data and cookies then check if the error gets fixed.

Alternatively, you may want to use a free multi-purpose utility such as Fortect. It not only clears the cache but removes any unnecessary data on the computer.

On Firefox

  1. Open Firefox, click on the hamburger icon at the top right corner, and click on Settings.
    firefox-settings-1
  2. Navigate to Privacy & Security and in the Cookies and Site Data section, click on Clear Data.
    500 internal server error NGINX
  3. Now click on Clear to confirm the process.
    500 internal server error NGINX
Read more about this topic

  • The Video Cannot be Played Error Code: 102630 [Fix]
  • Dataexchangehost.exe: What Is It Used For?
  • 3 Ways to Fix Request Header or Cookie Too Large

3. Disable VPN

  1. Press Windows key + I to open the Settings app.
  2. Navigate to Network & Internet.
  3. Select VPN from the left pane. In the right pane, pick your VPN connection and click on Remove.
    vpn remove
  4. If you’re using a VPN client, make sure to disconnect from the VPN.

Once done, restart your device and check if the 500 Internal Server Error NGINX is resolved.

4. Check your Internet connection

  1. Visit Fast i.e., a speed test website.
    Speed test
  2. As soon as the website opens it’ll automatically start testing your network’s speed.
  3. Wait while your connection is being tested.

If you don’t prefer this, you can use any other Internet speed tester to check your connection.

That’s all on how you can fix the 500 Internal Server Error in NGINX. Several issues are to be blamed, but this usually occurs due to a bad Internet connection. Things are no different for those complaining about getting the 500 Internal Server Error when using the React app

Follow the steps mentioned above to fix this error. If the troubleshooting methods mentioned above could not help you, feel free to drop a comment below. We’re eager to hear from you.

newsletter icon

Sometimes NGINX server may give 500 Internal Server Error due to various reasons. In this article we will look at what does 500 Internal Server Error mean in NGINX and how to fix 500 Internal Server Error in NGINX.

NGINX gives 500 Internal Server Error when there is a server-side error that prevents NGINX from returning a proper response. It can be due to many different reasons such as faulty script, missing files referenced by code, inadequate file permissions, etc. NGINX is typically used as a reverse proxy server, so the most common reason for 500 Internal server is an error in one of its web servers like Apache that has encountered an issue and returned a 500 error response to NGINX, which is then returned to client browsers. There are various ways to fix internal server error in NGINX.

Bonus Read : How To Fix 504 Gateway Timeout Error in NGINX

How to Fix 500 Internal Server Error in NGINX

Here are the steps to fix 500 Internal Server Error in NGINX on localhost, CPanel, PHP, Ubuntu and other platforms.

1. Hard Refresh

Sometimes you may get 500 internal server error in NGINX because your server is being restarted at that moment, or there are too many requests for web server to handle.

So it doesn’t have enough resources to serve your request.

In such cases, you can simply do a hard refresh of your page to force the browser to get latest web page version and fix 500 internal server error in NGINX. You can do this by pressing

  • Windows: Ctrl + F5
  • Mac: Apple + R or Cmd + R
  • Linux: F5

Bonus Read : How to Fix 502 Bad Gateway Error in NGINX

2. Examine Server Logs

Open your server log in a text editor to analyze the most recent requests. Every server log contains information about requested URLs and response code for each request.

Find out which requests result in 500 internal server error. It may be that only one page, or a few pages give this error while others work fine.

Find out which requests cause 500 internal server error. Once you have identified the problematic URLs, open a browser and request them again to confirm that is indeed the case.

Bonus Read : How to Increase Request Timeout in NGINX

3. Examine Your Script

Next, analyze the script to process the problematic requests. Is it actually present at the right location? Are you referencing it properly, in your URL mapping/routing file?

If your script refers to another file, find out if that file path is correct. If you have referenced any program/function, have you called it correctly?

4. Check File/Folder Permission

This can also be due to improper file/folder permissions. Did you add/modify any file/folder recently?

Typically, files need a 644 permission and folders need a 755 permission. You can use FileZilla (Windows) and Chmod (Linux) to modify file permissions.

You can also look at the permissions of other files & folders in your code and update the same for your files/folders accordingly.

Bonus Read : How to Increase File Upload Size in NGINX

5. Check redirections

If you have incorrectly setup any redirections in web server, it can give 500 internal server error. For example, if you use Apache web server, make sure you have properly configured mod_rewrite module and .htaccess file.

Also use a third-party tool to check the syntax of redirection/URL rewrite rules in your server configuration file.

6. Increase Script Timeout

You may also get 500 internal server error in NGINX if your web server (e.g Apache) is timing out on the request. In such cases, increase your web server (not NGINX) timeout value so that it stays connected to NGINX longer, and returns a proper response.

Hopefully, the above tips will help you fix 500 internal server error in NGINX.

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it Today!

Related posts:

  • About Author

mm

When I access 127.0.0.1:6789 it works fine, but when i try to access something like 127.0.0.1:6789/busca.html?q=a, I got 500 Internal Server Error

this is my nginx config file

server {

    listen   88;


    root /vagrant/rizqcursosonline/rizqcursosonline/frontend/wwwpublic;
    index index.php index.html index.htm;

    server_name example.com;

    location / {
            try_files $uri $uri/ /index.html;                
    }

    error_page 404 /404.html;

    error_page 500 502 503 504 /50x.html;
    location = /50x.html {
          root /vagrant/rizqcursosonline/rizqcursosonline/frontend/wwwpublic/;
    }

    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ .php$ {
            try_files $uri =404;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;

    }

}

nginx log error

2014/04/12 18:16:32 [error] 4165#0: *5 rewrite or internal redirection cycle while internally redirecting to "/index.html", client: 10.0.2.2, server: example.com, request: "GET /busca.html?q=a HTTP/1.1", host: "127.0.0.1:6789", referrer: "http://127.0.0.1:6789/"

2014/04/12 18:16:32 [error] 4165#0: *7 rewrite or internal redirection cycle while internally redirecting to «/index.html», client: 10.0.2.2, server: example.com, request: «GET /favicon.ico HTTP/1.1», host: «127.0.0.1:6789»

To start talking about the 500 internal server error Nginx, let’s clarify some terms.

This is a term applicable to a kind of server, characterized by belonging to the open source classification, additionally, Nginx provides the possibility of very low memory consumption, and allow without problems high concurrences, higher than 10,000 simultaneous connections.

500 internal server error, meaning

They are the acronym used to notify irregularities, inconveniences in a server, and that due to these, it is not possible to carry out the requested action.

The errors like this one, are notified according to the browsers in which one works, to the technical variety, to the functional that exists between the servers, since all are different, as far as structure, architecture, and capacities, also to the websites, these count on characteristics that most of the time are not similar, all these considerations are the cause so that the mentioned errors are shown in a variety of ways.

Although all variations convey the existence of a problem, 500 internal server error Nginx will always be understood, as the message displayed is explicit.

In addition, they are complemented through fragments with text with detailed data of what happens with this server, and why it is not possible to execute the action you want to perform, these details, and the way they are displayed vary depending on the type of server, being able to be completely blank screens, others are displayed customized, as the case of some famous sites, YouTube is one of them, Airbnb, and so each brand uses its customization to identify this message differentiating itself from others.

500 internal server error Nginx, what causes it?

Among the situations that originate the appearance of an error of this type, can be cataloged from various sources, there are a variety that occur very frequently, and the chances that these are the origin of the error are usually high.

  • Problems that prevent the proper functioning of the browser’s fastest storage layer.
  • Corruption problems, this occurs when trying to work with databases.
  • Some corrupted file, this occurs when requesting access to the website.
  • The server is not able at a given time.
  • With the login you try to access, this happens when you use it wrongly.
  • Folders and files with attributes different from the ones they have.
  • When it is on the PHP side, it happens directly because of trying to make use of a larger memory range than the established one.
  • Defective Htacces, these files in these conditions prevent the operation of the site.
  • Plugins, if they fail, the following error will appear

500 internal server error Nginx, Solutions for this error

They can appear in the part of the area corresponding to the user, or the part corresponding to the server, the important thing is to attack the problem quickly, so that the damages are minor, these can be some solutions:

Reload the page

You should start with an action that is recommended, and that in many cases is the fastest eliminating the problem, very simple, load the page again, just wait about 50 to 60 seconds, then proceed to the restart to display the page, just press F5, in some sites Ctrl followed by F5, the error will disappear if it was generated by the server not being protected against overload, after the action is done, it will be restored immediately.

Check where the problem is with a third party service

Downforeveryoneorjustme is an alternative to find an efficient way to eliminate this error, just copy the URL of the site where the error occurred, and you will get the information you need, the information you get will let you know which side is the problem, on yours, or if it is the server out of operation.

You can also check CloudFlare service status, as this very famous Cloud provider is protecting and redirecting most of the Internet traffic, as they act as a security layer between visitors browsers, like yourself experiencing this 500 Internal Server Error and the Web server to which you’ve requested a webpage.

If CloudFlare is actually not working and is experiencing a service issue, it will most likely be reflected by this issue on your browser — all you can do, is request a website that isn’t using CloudFlare, or, if it is your website, you can temporarily bypass CloudFlare with your own server configuration, however you will be exposed to security issues.

Clear cache

A 500 internal server error, can also be solved by eliminating the information that is in the Cache of the browser on which you are working, and additionally in your CDN cache if you are using one – if not, starting using a CDN caching solution would probably spare you from experiencing this issue.

Check server logs

Verification of the Server Logs, there are tools in each host, if you do not find them, there are codes to verify these records.

Increase PHP memory

In the cPanel of the page, you have the alternative of modifying the limit of the PHP memory, increasing the value that you have established.

Deactive plugins

Another option is to deactivate the set of Plugins.

To do it fast, simply change the names of the Plugins folders if you are using  the WordPress   CMS and your website will directly be accessible without any plugin activated.

Change server host

In last resort, if the issue is related to your webserver, it might be a good solution to switch to a better web hosting that will offer better performances and save you the trouble of finding why you are getting this error.

Conclusion: Solve problems

Errors like these can cause many damaging problems, and it is best to act immediately to eliminate them urgently.

Frequently Asked Questions

What does the server error code mean?
The error code indicates internal problems with the server that need to be diagnosed. A malfunction has occurred or the system configuration has been violated. In case of such an error, it is not necessary to immediately write to technical support. You can try to solve this problem yourself.

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 can’t establish a connection to the server at www.example.com

or

www.example.com refused to connect

or

The site can't be reached, www.example.com unexpectedly closed the connection.

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={http,https}, 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.

include /etc/nginx/conf.d/*;

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.

fork() failed while spawning "worker process" (12: Cannot allocate 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.

innodb_buffer_pool_size = 1024M
innodb_buffer_pool_dump_at_shutdown = ON
innodb_buffer_pool_load_at_startup  = ON
innodb_log_file_size = 512M
innodb_log_buffer_size = 8M

#Improving disk I/O performance
innodb_file_per_table = 1
innodb_open_files = 400
innodb_io_capacity = 400
innodb_flush_method = O_DIRECT
innodb_read_io_threads = 64
innodb_write_io_threads = 64
innodb_buffer_pool_instances = 3

Where:

  • 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.

sudo systemctl restart mariadb

Recommended reading: MySQL/MariaDB Database Performance Monitoring with Percona on Ubuntu Server

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).

"GET /apps/richdocumentscode/proxy.php?req=/hosting/capabilities HTTP/1.1" 499 0 "-" "Nextcloud Server Crawler"
"GET /apps/richdocumentscode/proxy.php?req=/hosting/capabilities HTTP/1.1" 499 0 "-" "Nextcloud Server Crawler"
"GET /apps/richdocumentscode/proxy.php?req=/hosting/capabilities HTTP/1.1" 499 0 "-" "Nextcloud Server Crawler"

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.

  proxy_connect_timeout       600;
  proxy_send_timeout          600;
  proxy_read_timeout          600;
  send_timeout                600;

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

 location ~ .php$ {
     try_files $uri /index.php$is_args$args;
     include snippets/fastcgi-php.conf;
     fastcgi_split_path_info ^(.+.php)(/.+)$;

     fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
     fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
     include fastcgi_params;
     fastcgi_read_timeout 300;
 }

Then reload Nginx.

sudo systemctl reload nginx

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

sudo nano /etc/php/7.4/fpm/php.ini

You can increase the value to 300 seconds.

max_execution_time = 300

Then restart PHP-FPM

sudo systemctl restart php7.4-fpm

Memory Size Exhausted

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

PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 57134520 bytes)

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

memory_limit = 512M

Then restart PHP7.4-FPM.

sudo systemctl 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/).

[error] 7553#7553: *2234677 upstream timed out (110: Connection timed out) while reading response header from upstream

Possible solutions:

  1. Restart PHP-FPM.
  2. Upgrade RAM.
  3. Optimize database performance. 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/).

connect() to unix:/run/php/php7.4-fpm.sock failed (11: Resource temporarily unavailable)

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.)

sudo nano /etc/php/7.4/fpm/pool.d/www.conf

The default child process config is as follows:

pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

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.)

pm = dynamic
pm.max_children = 20
pm.start_servers = 8
pm.min_spare_servers = 4
pm.max_spare_servers = 12

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

sudo nano /etc/php/7.4/fpm/php.ini

Find the following line.

memory_limit = 128M

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

memory_limit = 512M

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

sudo systemctl restart php7.4-fpm

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

;pm.status_path = /status

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

sudo systemctl restart php7.4-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.

location ~ ^/(status|ping)$ {
        allow 127.0.0.1;
        allow your_other_IP_Address;
        deny all;

        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_index index.php;
        include fastcgi_params;
        #fastcgi_pass 127.0.0.1:9000;
        fastcgi_pass   unix:/run/php/php7.4-fpm.sock;
}

Save and close the file. Then test Nginx configurations.

sudo nginx -t

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

sudo systemctl reload nginx

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.

listen.backlog = 511

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.

listen queue:         0
max listen queue:     0

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.

[email protected]:~$ sysctl net.core.somaxconn
net.core.somaxconn = 128

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

sudo nano /etc/sysctl.conf

Add the following two lines.

net.core.somaxconn = 20000
net.core.netdev_max_backlog = 65535

Save and close the file. Then apply the settings.

sudo sysctl -p

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.

pm = static
pm.max_children = 50

Two Virtual Host files For the Same Website

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

nginx: [warn] conflicting server name "example.com" on [::]:443, ignored
nginx: [warn] conflicting server name "example.com" on 0.0.0.0:443, ignored

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.

recv() failed (104: Connection reset by peer) while reading response header from upstream

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.

2021/09/28 13:27:41 [alert] 321#321: *120606 open socket #16 left in connection 163
2021/09/28 13:27:41 [alert] 321#321: *120629 open socket #34 left in connection 188
2021/09/28 13:27:41 [alert] 321#321: *120622 open socket #9 left in connection 213
2021/09/28 13:27:41 [alert] 321#321: *120628 open socket #25 left in connection 217
2021/09/28 13:27:41 [alert] 321#321: *120605 open socket #15 left in connection 244
2021/09/28 13:27:41 [alert] 321#321: *120614 open socket #41 left in connection 245
2021/09/28 13:27:41 [alert] 321#321: *120631 open socket #24 left in connection 255
2021/09/28 13:27:41 [alert] 321#321: *120616 open socket #23 left in connection 258
2021/09/28 13:27:41 [alert] 321#321: *120615 open socket #42 left in connection 269
2021/09/28 13:27:41 [alert] 321#321: aborting

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.

sudo pkill nginx
sudo systemctl restart nginx

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 🙂

You may want to check out:

  • How to Fix Common Let’s Encrypt/Certbot Errors

Nginx – очень популярный веб-сервер в наши дни.

В этой статье мы расскажем вам о некоторых распространенных ошибках при работе веб-сервера Nginx и возможных решениях.

Это не полный список.

Если вы все еще не можете устранить ошибку, попробовав предложенные решения, пожалуйста, проверьте логи сервера Nginx в каталоге /var/log/nginx/ и поищите в Google, чтобы отладить проблему.

Содержание

  1. Unable to connect/Refused to Connect
  2. The Connection Has Timed Out
  3. 404 Not Found
  4. 403 Forbidden
  5. 500 Internal Server Error
  6. Nginx показывает страницу по умолчанию
  7. 504 Gateway time-out
  8. Размер памяти исчерпан
  9. PR_END_OF_FILE_ERROR
  10. Resource temporarily unavailable
  11. Два файла виртуального хоста для одного и того же сайта
  12. PHP-FPM Connection reset by peer
  13. Утечки сокетов Nginx
  14. Заключение

Unable to connect/Refused to Connect

Если при попытке получить доступ к вашему сайту вы видите следующую ошибку:

Firefox can’t establish a connection to the server at www.example.com

или

www.example.com refused to connect

или

The site can't be reached, www.example.com unexpectedly closed the connection.

Это может быть потому, что:

  • Nginx не запущен. Вы можете проверить состояние Nginx с помощью sudo systemctl status nginx. Запустите Nginx с помощью sudo systemctl start nginx. Если Nginx не удается запустить, запустите sudo nginx -t, чтобы выяснить, нет ли ошибок в вашем конфигурационном файле. И проверьте логи (sudo journalctl -eu nginx), чтобы выяснить, почему он не запускается.
  • Брандмауэр блокирует порты 80 и 443. Если вы используете брандмауэр UFW на Debian/Ubuntu, выполните sudo ufw allow 80,443/tcp, чтобы открыть TCP порты 80 и 443. Если вы используете Firewalld на RHEL/CentOS/Rocky Linux/AlmaLinux, выполните sudo firewall-cmd –permanent –add-service={http,https}, затем sudo systemctl reload firewalld, чтобы открыть TCP порты 80 и 443.
  • Fail2ban. Если ваш сервер использует fail2ban для блокировки вредоносных запросов, возможно, fail2ban запретил ваш IP-адрес. Выполните команду sudo journalctl -eu fail2ban, чтобы проверить, не заблокирован ли ваш IP-адрес. Вы можете добавить свой IP-адрес в список fail2ban ignoreip, чтобы он больше не был забанен.
  • Nginx не прослушивает нужный сетевой интерфейс. Например, Nginx не прослушивает публичный IP-адрес сервера.

The Connection Has Timed Out

Это может означать, что ваш сервер находится в автономном режиме или Nginx работает неправильно.

Однажды у меня возникла проблема нехватки памяти, из-за чего Nginx не смог запустить рабочие процессы.

Если вы увидите следующее сообщение об ошибке в файле /var/log/nginx/error.log, вашему серверу не хватает памяти:

fork() failed while spawning "worker process" (12: Cannot allocate memory)

404 Not Found

404 not found означает, что Nginx не может найти ресурсы, которые запрашивает ваш веб-браузер.

🌐 Как создать пользовательскую страницу ошибки 404 в NGINX

Причина может быть следующей:

  • Корневой каталог web не существует на вашем сервере. В Nginx корневой веб-каталог настраивается с помощью директивы root, например, так: root /usr/share/nginx/linuxbabe.com/;. Убедитесь, что файлы вашего сайта (HTML, CSS, JavaScript, PHP) хранятся в правильном каталоге.
  • PHP-FPM не запущен. Вы можете проверить статус PHP-FPM с помощью sudo systemctl status php7.4-fpm (Debian/Ubuntu) или sudo systemctl status php-fpm.
  • Вы забыли включить директиву try_files $uri /index.php$is_args$args; в конфигурационный файл сервера Nginx. Эта директива необходима для обработки PHP-кода.
  • На вашем сервере нет свободного дискового пространства. Попробуйте освободить немного дискового пространства. Вы можете использовать утилиту ncdu (sudo apt install ncdu или sudo dnf install ncdu), чтобы узнать, какие каталоги занимают огромное количество дискового пространства.

403 Forbidden

Эта ошибка означает, что вам не разрешен доступ к ресурсам запроса.

Возможный сценарий включает:

  • Администратор сайта блокирует публичный доступ к запрашиваемым ресурсам с помощью белого списка IP-адресов или других методов.
  • На сайте может использоваться брандмауэр веб-приложения, например ModSecurity, который обнаружил атаку вторжения, поэтому заблокировал запрос.
    Некоторые веб-приложения могут показывать другое сообщение об ошибке, когда происходит запрет 403. Оно может сказать вам, что “secure connection failed, хотя причина та же.

500 Internal Server Error

Это означает, что в веб-приложении произошла какая-то ошибка.

Это может быть следующее

  • Сервер базы данных не работает. Проверьте состояние MySQL/MariaDB с помощью sudo systemctl status mysql. Запустите его с помощью sudo systemctl start mysql. Запустите sudo journalctl -eu mysql, чтобы выяснить, почему он не запускается. Процесс MySQL/MariaDB может быть завершен из-за проблем с нехваткой памяти.
  • Вы не настроили Nginx на использование PHP-FPM, поэтому Nginx не знает, как выполнять PHP-код.
  • Если ваше веб-приложение имеет встроенный кэш, вы можете попробовать очистить кэш приложения, чтобы исправить эту ошибку.
  • Ваше веб-приложение может создавать свой собственный журнал ошибок. Проверьте этот файл журнала, чтобы отладить эту ошибку.
  • Возможно, в вашем веб-приложении есть режим отладки. Включите его, и вы увидите более подробные сообщения об ошибках на веб-странице. Например, вы можете включить режим отладки в почтовом сервере хостинг-платформы Modoboa, установив DEBUG = True в файле /srv/modoboa/instance/instance/settings.py.
  • PHP-FPM может быть перегружен. Проверьте журнал PHP-FPM (например, /var/log/php7.4-fpm.log). Если вы обнаружили предупреждение [pool www] seems busy (возможно, вам нужно увеличить pm.start_servers, или pm.min/max_spare_servers), вам нужно выделить больше ресурсов для PHP-FPM.
  • Иногда перезагрузка PHP-FPM (sudo systemctl reload php7.4-fpm) может исправить ошибку.

Nginx показывает страницу по умолчанию

Если вы пытаетесь настроить виртуальный хост Nginx и при вводе доменного имени в веб-браузере отображается страница Nginx по умолчанию, это может быть следующее

  • Вы не использовали реальное доменное имя для директивы server_name в виртуальном хосте Nginx.
  • Вы забыли перезагрузить Nginx.

504 Gateway time-out

Это означает, что апстрим, такой как PHP-FPM/MySQL/MariaDB, не может обработать запрос достаточно быстро.

Вы можете попробовать перезапустить PHP-FPM, чтобы временно исправить ошибку, но лучше начать настраивать PHP-FPM/MySQL/MariaDB для более быстрой работы.

Вот конфигурация InnoDB в моем файле /etc/mysql/mariadb.conf.d/50-server.cnf.

Это очень простая настройка производительности.

innodb_buffer_pool_size = 1024M
innodb_buffer_pool_dump_at_shutdown = ON
innodb_buffer_pool_load_at_startup  = ON
innodb_log_file_size = 512M
innodb_log_buffer_size = 8M

#Improving disk I/O performance
innodb_file_per_table = 1
innodb_open_files = 400
innodb_io_capacity = 400
innodb_flush_method = O_DIRECT
innodb_read_io_threads = 64
innodb_write_io_threads = 64
innodb_buffer_pool_instances = 3

Где:

  • InnoDB buffer pool size должен быть не менее половины вашей оперативной памяти. (Для VPS с небольшим объемом оперативной памяти я рекомендую установить размер буферного пула на меньшее значение, например 400M, иначе ваш VPS будет работать без оперативной памяти).
  • InnoDB log file size должен составлять 25% от размера буферного пула.
  • Установите потоки ввода-вывода для чтения и записи на максимум (64).
  • Заставьте MariaDB использовать 3 экземпляра буферного пула InnoDB. Количество экземпляров должно соответствовать количеству ядер процессора в вашей системе.
  • После сохранения изменений перезапустите MariaDB.

После сохранения изменений перезапустите MariaDB.

sudo systemctl restart mariadb

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

Отредактируйте файл виртуального хоста Nginx и добавьте следующие строки в блок server {…}.

  proxy_connect_timeout       600;
  proxy_send_timeout          600;
  proxy_read_timeout          600;
  send_timeout                600;

Если вы используете Nginx с PHP-FPM, то установите для параметра fastcgi_read_timeout большее значение, например 300 секунд.

По умолчанию это 60 секунд.

 location ~ .php$ {
     try_files $uri /index.php$is_args$args;
     include snippets/fastcgi-php.conf;
     fastcgi_split_path_info ^(.+.php)(/.+)$;

     fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
     fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
     include fastcgi_params;
     fastcgi_read_timeout 300;
 }

Затем перезагрузите Nginx.

sudo systemctl reload nginx

PHP-FPM также имеет максимальное время выполнения для каждого скрипта.

Отредактируйте файл php.ini.

sudo nano /etc/php/7.4/fpm/php.ini

Вы можете увеличить это значение до 300 секунд.

max_execution_time = 300

Затем перезапустите PHP-FPM

sudo systemctl restart php7.4-fpm

Размер памяти исчерпан

Если вы видите следующую строку в журнале ошибок Nginx, это означает, что PHP достиг лимита памяти в 128 МБ.

PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 57134520 bytes)

Вы можете отредактировать файл php.ini (/etc/php/7.4/fpm/php.ini) и увеличить лимит памяти PHP.

memory_limit = 512M

Затем перезапустите PHP7.4-FPM.

sudo systemctl restart php7.4-fpm

Если ошибка все еще существует, скорее всего, в вашем веб-приложении плохой PHP-код, который потребляет много оперативной памяти.

PR_END_OF_FILE_ERROR

  1. Вы настроили Nginx на перенаправление HTTP-запросов на HTTPS, но в Nginx нет блока сервера, обслуживающего HTTPS-запросы.
  2. Может быть, Nginx не запущен?
  3. Иногда основной бинарник Nginx запущен, но рабочий процесс может не работать и завершиться по разным причинам. Для отладки проверьте логи ошибок Nginx (/var/log/nginx/error.log).

Resource temporarily unavailable

Некоторые пользователи могут найти следующую ошибку в файле логов ошибок Nginx (в разделе /var/log/nginx/).

connect() to unix:/run/php/php7.4-fpm.sock failed (11: Resource temporarily unavailable)

Обычно это означает, что на вашем сайте много посетителей и PHP-FPM не справляется с обработкой огромного количества запросов.

Вы можете изменить количество дочерних процессов PHP-FPM, чтобы он мог обрабатывать больше запросов.

Отредактируйте файл PHP-FPM www.conf.

(Путь к файлу зависит от дистрибутива Linux).

sudo /etc/php/7.4/fpm/pool.d/www.conf

По умолчанию конфигурация дочернего процесса выглядит следующим образом:

pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3

Приведенная выше конфигурация означает.

  • PHP-FPM динамически создает дочерние процессы. Нет фиксированного количества дочерних процессов.
  • Создается не более 5 дочерних процессов.
  • При запуске PHP-FPM запускаются 2 дочерних процесса.
  • Есть как минимум 1 незанятый процесс.
  • Максимум 3 неработающих процесса.
pm = dynamic
pm.max_children = 20
pm.start_servers = 8
pm.min_spare_servers = 4
pm.max_spare_servers = 12

Убедитесь, что у вас достаточно оперативной памяти для запуска дополнительных дочерних процессов.

Сохраните и закройте файл.

Затем перезапустите PHP-FPM. (Возможно, вам потребуется изменить номер версии).

sudo systemctl restart php7.4-fpm

Чтобы следить за состоянием PHP-FPM, вы можете включить страницу status .

Найдите следующую строку в файле PHP-FPM www.conf.

Обратите внимание, что

;pm.status_path = /status

Уберите точку с запятой, чтобы включить страницу состояния PHP-FPM.

Затем перезапустите PHP-FPM.

sudo systemctl restart php7.4-fpm

Затем отредактируйте файл виртуального хоста Nginx.

Добавьте следующие строки.

Директивы allow и deny используются для ограничения доступа.

Только IP-адреса из “белого списка” могут получить доступ к странице состояния.

location ~ ^/(status|ping)$ {
        allow 127.0.0.1;
        allow your_other_IP_Address;
        deny all;

        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_index index.php;
        include fastcgi_params;
        #fastcgi_pass 127.0.0.1:9000;
        fastcgi_pass   unix:/run/php/php7.4-fpm.sock;
}

Сохраните и закройте файл. Затем протестируйте конфигурацию Nginx.

sudo nginx -t

Если проверка прошла успешно, перезагрузите Nginx, чтобы изменения вступили в силу.

sudo systemctl reload nginx

В файле PHP-FPM www.conf дается хорошее объяснение того, что означает каждый параметр.

Если PHP-FPM очень занят и не может обслужить запрос немедленно, он поставит его в очередь.

По умолчанию может быть не более 511 ожидающих запросов, определяемых параметром listen.backlog.

listen.backlog = 511

Если вы видите следующее значение на странице состояния PHP-FPM, это означает, что в очереди еще не было ни одного запроса, т.е. ваш PHP-FPM может быстро обрабатывать запросы.

listen queue:         0
max listen queue:     0

Если в очереди 511 ожидающих запросов, это означает, что ваш PHP-FPM очень загружен, поэтому вам следует увеличить количество дочерних процессов.

Вам также может понадобиться изменить параметр ядра Linux net.core.somaxconn, который определяет максимальное количество соединений, разрешенных к файлу сокетов в Linux, например, к файлу сокетов PHP-FPM Unix.

По умолчанию его значение равно 128 до ядра 5.4 и 4096 начиная с ядра 5.4.

$ sysctl net.core.somaxconn
net.core.somaxconn = 128

Если у вас сайт с высокой посещаемостью, вы можете использовать большое значение.

Отредактируйте файл /etc/sysctl.conf.

sudo nano /etc/sysctl.cnf

Добавьте следующие две строки.

net.core.somaxconn = 20000
net.core.netdev_max_backlog = 65535

Сохраните и закройте файл. Затем примените настройки.

sudo sysctl -p

Примечание: Если ваш сервер имеет достаточно оперативной памяти, вы можете выделить фиксированное количество дочерних процессов для PHP-FPM, как показано ниже.

Два файла виртуального хоста для одного и того же сайта

Если вы запустите sudo nginx -t и увидите следующее предупреждение.

nginx: [warn] conflicting server name "example.com" on [::]:443, ignored
nginx: [warn] conflicting server name "example.com" on 0.0.0.0:443, ignored

Это означает, что есть два файла виртуальных хостов, содержащих одну и ту же конфигурацию server_name.

Не создавайте два файла виртуальных хостов для одного сайта.

PHP-FPM Connection reset by peer

В файле логов ошибок Nginx отображается следующее сообщение.

recv() failed (104: Connection reset by peer) while reading response header from upstream

Это может быть вызвано перезапуском PHP-FPM.

Если он перезапущен вручную самостоятельно, то вы можете игнорировать эту ошибку.

Утечки сокетов Nginx

Если вы обнаружили следующее сообщение об ошибке в файле /var/log/nginx/error.log, значит, у вашего Nginx проблема с утечкой сокетов.

2021/09/28 13:27:41 [alert] 321#321: *120606 open socket #16 left in connection 163
2021/09/28 13:27:41 [alert] 321#321: *120629 open socket #34 left in connection 188
2021/09/28 13:27:41 [alert] 321#321: *120622 open socket #9 left in connection 213
2021/09/28 13:27:41 [alert] 321#321: *120628 open socket #25 left in connection 217
2021/09/28 13:27:41 [alert] 321#321: *120605 open socket #15 left in connection 244
2021/09/28 13:27:41 [alert] 321#321: *120614 open socket #41 left in connection 245
2021/09/28 13:27:41 [alert] 321#321: *120631 open socket #24 left in connection 255
2021/09/28 13:27:41 [alert] 321#321: *120616 open socket #23 left in connection 258
2021/09/28 13:27:41 [alert] 321#321: *120615 open socket #42 left in connection 269
2021/09/28 13:27:41 [alert] 321#321: aborting

Вы можете перезапустить ОС, чтобы решить эту проблему.

Если это не помогает, вам нужно скомпилировать отладочную версию Nginx, которая покажет вам отладочную информацию в логах.

Заключение

Надеюсь, эта статья помогла вам исправить распространенные ошибки веб-сервера Nginx.

см. также:

  • 🌐 Как контролировать доступ на основе IP-адреса клиента в NGINX
  • 🐉 Настройка http-сервера Kali Linux
  • 🌐 Как парсить логи доступа nginx
  • 🌐 Ограничение скорости определенных URL-адресов с Nginx
  • 🛡️ Как использовать обратный прокси Nginx для ограничения внешних вызовов внутри веб-браузера
  • 🔏 Как настроить Nginx с Let’s Encrypt с помощью ACME на Ubuntu
  • 🌐 Как собрать NGINX с ModSecurity на Ubuntu сервере

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