When I try to access say: Http://localhost/page
I get a 500 Internal Server Error from nginx. 500 Internal Server Error nginx/1.1.19
is all it states on the page.
In the log file I get this error: 2014/07/06 17:56:32 [error] 2056#0: *2 rewrite or internal redirection cycle while internally redirecting to "/index.html", client: 127.0.0.1, server: localhost, request: "GET /download HTTP/1.1", host: "localhost"
EDIT: It looks like it is an issue with the Routes I set for laravel not taking effect. Because that last error means it is doing a redirect loop to index.php. I changed try_files $uri $uri/ /index.html;
to try_files $uri $uri/ =404;
and now it is just giving the 404 page. And now there is no error.
I am using a LEMP stack for my local server for the time being until I can get Laravel Homestead working with Vagrant and Oracle VM. I have set everything up according to this walkthrough.
Everything is working fine, I have nginx and php5 running fine. I was able to easily install php5-mcrypt so that composer would work, and the last thing I have done is change the root directory for nginx to be my project’s public folder for Laravel. (So that our link calls could reference the root with / and work).
My nginx.conf File:
user www-data;
worker_processes 4;
pid /var/run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;
# server_names_hash_bucket_size 64;
# server_name_in_redirect off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
# gzip_vary on;
# gzip_proxied any;
# gzip_comp_level 6;
# gzip_buffers 16 8k;
# gzip_http_version 1.1;
# gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
##
# nginx-naxsi config
##
# Uncomment it if you installed nginx-naxsi
##
#include /etc/nginx/naxsi_core.rules;
##
# nginx-passenger config
##
# Uncomment it if you installed nginx-passenger
##
#passenger_root /usr;
#passenger_ruby /usr/bin/ruby;
##
# Virtual Host Configs
##
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
#mail {
# # See sample authentication script at:
# # http://wiki.nginx.org/ImapAuthenticateWithApachePhpScript
#
# # auth_http localhost/auth.php;
# # pop3_capabilities "TOP" "USER";
# # imap_capabilities "IMAP4rev1" "UIDPLUS";
#
# server {
# listen localhost:110;
# protocol pop3;
# proxy on;
# }
#
# server {
# listen localhost:143;
# protocol imap;
# proxy on;
# }
#}
My default file in /etc/nginx/sites-available/:
# server {
# ...
# }
# statements for each of your virtual hosts to this file
##
# You should look at the following URL's in order to grasp a solid understanding
# of Nginx configuration files in order to fully unleash the power of Nginx.
# http://wiki.nginx.org/Pitfalls
# http://wiki.nginx.org/QuickStart
# http://wiki.nginx.org/Configuration
#
# Generally, you will want to move this file somewhere, and start with a clean
# file but keep this around for reference. Or just disable in sites-enabled.
#
# Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples.
##
server {
listen 80; ## listen for ipv4; this line is default and implied
#listen [::]:80 default ipv6only=on; ## listen for ipv6
root /usr/share/nginx/www/DDbuddy/public;
index index.php index.html index.htm;
# Make site accessible from http://localhost/
server_name localhost;
location / {
# First attempt to serve request as file, then
# as directory, then fall back to index.html
try_files $uri $uri/ /index.html;
# Uncomment to enable naxsi on this location
# include /etc/nginx/naxsi.rules
}
location /doc/ {
alias /usr/share/doc/;
autoindex on;
allow 127.0.0.1;
deny all;
}
# Only for nginx-naxsi : process denied requests
#location /RequestDenied {
# For example, return an error code
#return 418;
#}
error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/www;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ .php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+.php)(/.+)$;
# # NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
#
# # With php5-cgi alone:
fastcgi_pass 127.0.0.1:9000;
# # With php5-fpm:
# fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# root html;
# index index.html index.htm;
#
# location / {
# try_files $uri $uri/ /index.html;
# }
#}
# HTTPS server
#
#server {
# listen 443;
# server_name localhost;
#
# root html;
# index index.html index.htm;
#
# ssl on;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
#
# ssl_session_timeout 5m;
#
# ssl_protocols SSLv3 TLSv1;
# ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv3:+EXP;
# ssl_prefer_server_ciphers on;
#
# location / {
# try_files $uri $uri/ /index.html;
# }
#}
In the nginx.conf file I set worker_processes to the default of 4, event though this is running on my laptop and I’m pretty sure I only have one processor. I had it set to 1, but I read on another through that that might be the issue. But I can change it back if needed.
При разработке веб-сайтов и веб-приложений можно столкнуться с ошибкой 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. Как видите проблема вполне решаема и в большинстве случаев вам помогут действия описанные в статье. А если не помогут, напишите свое решение в комментариях!
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
Osman Forhad
Posted on Jan 20, 2021
• Updated on Mar 12, 2022
Basically, internal server error 500 is Laravel errors it’s not related to javascript or any other, to check this error go to chrome inspect->network and see the response.
it would be looks like the below screenshot.
This type of issue must be in controller related issue to solve this you have to check your controller function is written well,
.
and then you should check your router file whether (web.php or api.php) where you mention your controller file is properly.
.
If you are confused about why it’s happened and it too much worries you.
.
Here is another easy method to find out what is happening wrong. And this is your Laravel log file. Please check your Laravel log file. Hope you will find out your issue and solve it properly.
.
Happy Coding.
osman forhad
Mobile & Web Application Developer💻
Super Useful CSS Resources
A collection of 70 hand-picked, web-based tools which are actually useful.
Each will generate pure CSS without the need for JS or any external libraries.
Read next
Carbon isPast & isFuture methods | Laravel | How to | Tutorial | Quick Win Wednesday #QWW
Bert De Swaef — Aug 31 ’22
Laravel 8 Custom Email Verification Tutorial
Techsolutionstuff — Oct 4 ’22
Pokedex: Utilizando Livewire para el front.
Chris López — Sep 13 ’22
Some important features of this release Laravel 9.30
Morcos Gad — Sep 20 ’22
Once unpublished, all posts by osmanforhad will become hidden and only accessible to themselves.
If osmanforhad is not suspended, they can still re-publish their posts from their dashboard.
Note:
Once unpublished, this post will become invisible to the public and only accessible to Osman Forhad.
They can still re-publish the post if they are not suspended.
Thanks for keeping DEV Community 👩💻👨💻 safe. Here is what you can do to flag osmanforhad:
Make all posts by osmanforhad less visible
osmanforhad consistently posts content that violates DEV Community 👩💻👨💻’s
code of conduct because it is harassing, offensive or spammy.
- June 6, 2017
- Laravel
When you get an error 500 screen with a red bar at the top stating Whoops, looks like something went wrong. running your Laravel app you might spend a lot of time debugging your Nginx configuration like I did before. You will be looking at the wrong place. Here is what is up and how you can solve this.
Laravel Error
This error you are getting in the top bar besides the general error 500 warning in the access logs probably at /var/log/nginx/error.log stating Whoops, looks like something went wrong followed by the ghost icon and word Exception is a Laravel error. The red bar and text is generated by Laravel , not Nginx!. So you should check the Laravel log to see what is up. And perhaps you have not turned on Laravel logging properly so you will then need to add:
APP_ENV=local
to the .env file. In my case the issue was that is was all empty as I was working on setting up a new deployment mechanism.
NB If if it was not for you and you did have this line then you simply need to check the log.
Laravel Logging
With error logging now finally working (if you did had an empty .env as me before) you will start logging in Laravel. You will be able to see this kind of error in storage/logs/laravel.log :
production.ERROR: RuntimeException: The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths. in /var/www/domain.com/releases/1/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:43
followed by the full stack trace. This as you are also missing your Laravel key in the .env as well.
Generating Laravel Key
To fix this missing key issue do a:
php artisan key:generate
Then copy the output in the brackets, and put it in your .env file as:
APP_KEY=base64:keygoeshere
Clearing Laravel Cache
Then you need to clear the cache to load the new key / .env changes. To do this do a:
php artisan config:clear
followed by a:
php artisan config:cache
Now you should be able to see the Laravel welcome page or whatever page you have set up to load as the main page for the domain.
Tagged in : Tagged in : error 500, laravel
Jasper Frumau
Jasper has been working with web frameworks and applications such as Laravel, Magento and his favorite CMS WordPress including Roots Trellis and Sage for more than a decade. He helps customers with web design and online marketing. Services provided are web design, ecommerce, SEO, content marketing. When Jasper is not coding, marketing a website, reading about the web or dreaming the internet of things he plays with his son, travels or run a few blocks.
Related Articles
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
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.
Posted 4 years ago by Ryan Dhungel
Category: JavaScript React Laravel
Viewed 18988 times
Estimated read time: 2 minutes
Have you been getting 500 Internal Server Error in your Laravel project every time you make a POST request from JavaScript side of your application using Vue JS or React JS?
There might be three possible reasons
- You are not using the correct post route
- You have not set the protected fillable fields in your model
- You are not sending all required fields for example title and body
Possible solutions
Make sure you are using post route such as Route::post(‘/blogs’);
Set the fillable fields, for example here on my Blog model, I have set these fields fillable:
protected $fillable = ['title', 'body'];
Send all the required fields in your post request. Here I have send the title and body as POST request from react component using axios
axios
.post('/blog/store', {
title: this.state.title,
body: this.state.body
})
.then(response => {
console.log('from handle submit', response);
});
you can also try setting mysql strict mode to false in config/database.php and see what happens:
'strict' => false,
It changing strict to false fixes the issue, then you are not sending all the fields on your post request.
Easy debugging:
When you make such GET or POST request from JavaScript side of your application, always open the network tab in the google chrome console and click on the post link that appears. Click on that link and click on Preview tab to see the error messages etc.
Hope you were able to pass through your error messages. If so.. congrats!