My laravel installation was working fine yesterday but today I get the following error:
Forbidden
You don't have permission to access / on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.
Does anyone know where I am going wrong?
asked Aug 16, 2013 at 11:44
2
Create and put this .htaccess file in your laravel installation(root) folder.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
answered Apr 20, 2015 at 13:12
AlexeyAlexey
7,0299 gold badges58 silver badges93 bronze badges
4
For me, It was just because I had a folder in my public_html named as same as that route!
so please check if you don’t have a folder with the address of that route!
hope be helpful
answered Sep 3, 2018 at 4:16
AliAli
1,4351 gold badge15 silver badges27 bronze badges
5
I met the same issue, then I do same as the solution of @lubat and my project work well.
My virtualhost configuration:
<VirtualHost *:80>
ServerName laravelht.vn
DocumentRoot D:/Lavarel/HTPortal/public
SetEnv APPLICATION_ENV "development"
<Directory D:/Lavarel/HTPortal/public>
DirectoryIndex index.php
AllowOverride All
Require all granted
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
answered Oct 8, 2015 at 8:06
0
Check your virtual host configuration.
For Ubuntu you could find it at /etc/apache2/sites-available/yourlaravel.conf
It should be like this:
<VirtualHost *:80>
ServerName yourlaravel.com
DocumentRoot "/path/to/your/laravel/project/public"
ServerAlias *.yourlaravel.com
<Directory "/path/to/your/laravel/project/public">
AllowOverride All
Require all granted
</Directory>
The key line is Require all granted
inside <Directory>
.
Hope it helps!
answered Jul 30, 2015 at 10:21
lubartlubart
1,7063 gold badges27 silver badges35 bronze badges
Have you tried to change the .htaccess file that laravel suggested if the default one doesn’t work? I had this similar problem and changed it to
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
and it soleved
answered Aug 17, 2013 at 7:34
2
Just add a .htaccess
file in your root project path with the following code to redirect to the public folder:
.HTACCESS
## Redirect to public folder
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^$ public/ [L]
RewriteRule (.*) public/$1 [L]
</IfModule>
Very simple but work for me in my server.
Regards!
answered Apr 3, 2018 at 17:57
2
It was solved for me with the Laravel default public/.htaccess file adding an extra line:
The /public/.htaccess
file remains as follows:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
DirectoryIndex index.php # <--- This line
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
answered Jul 20, 2016 at 20:41
EvhzEvhz
8,6458 gold badges50 silver badges69 bronze badges
0
For those who using Mamp or Mamp pro:
Open MAMP Pro
Click on “Hosts”
Click on “Extended” (UPDATE: Only if you are using MAMP Pro 3.0.6)
Check “Indexes”
Click “Save”
That’s it! Reload your localhost starting page and it should work properly.
answered Dec 28, 2014 at 12:30
DPPDPP
12.5k3 gold badges49 silver badges46 bronze badges
0
With me the problem appeared to be about the fact that there was no index.php file in the public_html folder. When I typed in this address however: http://azxcvfj.org/public , it worked (this address is just an example. It points to nowhere). This made me think and eventually I solved it by doing the following.
I made a .htaccess file in the app’s root folder (the public_html folder) with this contents:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes...
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ public/index.php [L]
</IfModule>
And this worked. With this file you are basically saying to the server (Apache) that whenever someone is trying to access the public html folder(http://azxcvfj.org) that someone who is being redirected is redirected to http://azxcvfj.org/public/index.php
answered Nov 9, 2014 at 17:26
PieterVKPieterVK
1,4631 gold badge10 silver badges4 bronze badges
First, update your Virtual Host configuration;
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html/example-project/public
<Directory /var/www/html/example-project/public/>
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Then, change both permission and ownership of the asset as illustrated below.
$ sudo chgrp -R www-data /var/www/html/example-project
$ sudo chmod -R 775 /var/www/html/example-project
nyedidikeke
6,5427 gold badges44 silver badges56 bronze badges
answered Aug 20, 2017 at 16:56
YvesYves
78614 silver badges17 bronze badges
In your VirtualHost write the DocumentRoot to point to your Laravel Application in your home directories. In addition you must add the Directory shown below, with your own path:
<Directory /home/john/Laravel_Projects/links/public/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
allow from all
Require all granted
</Directory>
The second step, you must go to your Laravel Project and run the following command.
sudo chmod -R 777 storage bootstrap/cache
At the end restart your apache2:
sudo service apache2 restart
answered Dec 5, 2018 at 4:31
2
This is solved my problem by adding this line:
DirectoryIndex index.php
Grant Miller
26.5k16 gold badges144 silver badges159 bronze badges
answered Jun 3, 2018 at 0:18
In my case, this error was due to internal links in the server, PHP wasn’t able to access those folders unless the proper option for that was added to .htaccess
.
Add the following line after RewriteEngine On
:
Options +FollowSymLinks
answered Nov 19, 2019 at 17:53
António AlmeidaAntónio Almeida
9,3358 gold badges60 silver badges65 bronze badges
1
Chances are that, if all the answers above didn’t work for you, and you are using a request validation, you forgot to put the authorization to true.
<?php
namespace AppHttpRequests;
use IlluminateFoundationHttpFormRequest;
class EquipmentRequest extends FormRequest {
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize() {
/*******************************************************/
return true; /************ THIS VALUE NEEDS TO BE TRUE */
/*******************************************************/
}
/* ... */
}
answered Jun 4, 2018 at 14:15
Amin NAIRIAmin NAIRI
2,17421 silver badges19 bronze badges
1
If you have tried all .htaccess answers from comments and none of them worked, it’s possible that actually you have bad APP_URL in you .env config file.
That worked for me.
answered Oct 23, 2019 at 21:45
0
For my case was encountering this issue with Laravel 6.x and managed to sort it out by installing an SSL Certificate. Tried playing around with .htaccess but never worked. I’m using the default Laravel 6.x .htaccess file which has the following contents
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
answered Mar 9, 2020 at 15:05
1
Check your project root directory index.php file. I think your index.php file missing.
<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylor@laravel.com>
*/
$uri = urldecode(
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);
// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
return false;
}
require_once __DIR__.'/public/index.php';
then check your project root directory .htaccess file
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
I hope your problem solved thank you.
answered Jun 16, 2022 at 4:25
Remember that Laravel’s project root is /public
The solution for me was so simple it was silly — I had moved my folders and updated the paths in my Apache server’s virtual hosts configuration (extra/httpd-vhosts.conf
for XAMPP), but had forgotten that Laravel’s app root is located at /public
. Simply updating:
D:UsersMeDocumentsProjectsWebsitesmyproject
to
D:UsersMeDocumentsProjectsWebsitesmyprojectpublic
…and then restarting the server solved the issue.
answered Jul 1, 2022 at 19:49
Hashim AzizHashim Aziz
3,4704 gold badges35 silver badges62 bronze badges
In my case, the index.php
file was missing from the Laravel root project, this also caused 403 error forbidden, creating a new file and put this code on it got the job done.
<?php
/**
* Laravel - A PHP Framework For Web Artisans
*
* @package Laravel
* @author Taylor Otwell <taylor@laravel.com>
*/
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/
require __DIR__.'/vendor/autoload.php';
/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/
$kernel = $app->make(IlluminateContractsHttpKernel::class);
$response = $kernel->handle(
$request = IlluminateHttpRequest::capture()
);
$response->send();
$kernel->terminate($request, $response);
answered Jul 24, 2022 at 8:30
WardNsourWardNsour
3151 gold badge2 silver badges16 bronze badges
I had the same problem and builded a .htaccess
file to fix this issue with a few more improvements. You can use it as it is, just download it from Github Gist and change the filename «public/index.php» to «public/app.php» and see how it works!
answered Jul 3, 2015 at 20:21
dudedude
5,4289 gold badges54 silver badges80 bronze badges
For me this was simply calling route()
on a named route that I had not created/created incorrectly. This caused the Forbidden error page.
Restarting the web server allowed proper Whoops! error to display:
Route [my-route-name] not defined.
Fixing the route name ->name('my-route-name')
fixed the error.
This is on Laravel 5.5 & using wampserver.
answered Mar 3, 2018 at 2:46
AndrewAndrew
17.8k12 gold badges102 silver badges112 bronze badges
I had this error and i just pasted the http://127.0.0.1:8000/ directly into the url bar.
you get the below when you type : php laravel serve
i was putting in localhost/http://127.0.0.1:8000/ to get the error you mentioned.
answered Nov 26, 2018 at 0:01
On public/.htaccess edit to
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
In the root of the project add file
Procfile
File content
web: vendor/bin/heroku-php-apache2 public/
Reload the project to Heroku
bash
heroku login
cd my-project/
git init
heroku git:remote -a my project
git add .
git commit -am "make it better"
git push heroku master
heroku open
Theo
55.6k8 gold badges23 silver badges40 bronze badges
answered Aug 6, 2019 at 11:37
0
The problem is the location of the index file (index.php).You must create a symbolic link in the root of the project to public/index.php with the command «ln-s public/index.php index.php«
answered Sep 5, 2019 at 12:24
Heretic SicHeretic Sic
3242 silver badges9 bronze badges
You might be facing the file permissions issue. Verify your htacces file, did it change from yesterday ? Also, if you were doing any «composer update» or «artisan optimize» stuff, try chowning your laravel project folder for your username.
chown -R yourusername yourlaravelappfolder
EDIT: the problem is possibly due to your local file permissions concerning Vagrant. Try to
set the permissions to the Vagrantfile containing folder to 777
answered Aug 16, 2013 at 11:47
GadomaGadoma
6,3951 gold badge29 silver badges34 bronze badges
7
I’ve found solution
I put following code into my public/.htaccess
and now its running at rocket speed
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
answered Jan 13, 2020 at 8:30
1
Laravel error 403 is one of the most common and annoying errors.
It mainly occurs due to improper permissions, ownerships, or any trouble with the .htaccess file and also missing directives.
Here at Bobcares, we usually receive many requests for fixing Laravel errors as a part of our Server Management Services.
Today, let’s see how our Support Engineers fix it.
How we fix Laravel error 403
Now let’s now see how our Support Engineers fix this error efficiently.
1. Check the permissions and ownership
Whenever we receive this error our Support Engineers initially check the permissions and ownerships of the files and folders.
And confirm that the permissions and the ownership of the files and folders are set correctly because this is one of the common reasons for this error to occur.
2. Checking the .htaccess file.
The .htaccess file also plays a major role in throwing the error message. So, we check if there are any incorrect codes in it. If so, then we either remove the code or rename the .htaccess file.
Here is the command that we run to rename the .htacess file.
mv .htaccess .htaccess-bck
3. Missing directives
Recently, one of our customers approached us with this error message on his Laravel website.
After fixing the permissions and checking the .htaccessfile, we checked for the virtual host configuration file httpd.conf placed in the path /etc/httpd/conf.d. We could see that the AllowOverride directive was missing in the configuration file.
Hence, the .htaccess file was not getting parsed by apache because the AllowOverride All directive was missing.
So, we added the below code in the virtual host configuration file.
Then we restarted Apache using the command
service httpd restart
After this, we cleared the cache and cookies. Finally, we could see the website to be working well and the error 403 disappeared.
[Need assistance in fixing Laravel errors? – We’ll help you]
Conclusion
In short, this error mainly occurs due to bad permissions, improper ownerships and incorrect .htaccess file. Today, we saw how our Support Engineers fix this error message.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;
Laravel is primarily used for building custom web apps using PHP. It’s a web framework that handles many things that are annoying to build yourself, such as routing, templating HTML, and authentication.
Laravel is one of the best PHP web frameworks, but there are many other frameworks in different languages.
Laravel error 403 is one of the most common and annoying errors.
It mainly occurs due to improper permissions, ownerships, or any trouble with the .htaccess file and also missing directives.
The simple reason why we are seeing this error is that you are trying to access something you don’t have the permission for.
Throwing a 403 forbidden error is your website’s way of stating that you don’t have enough permissions to proceed further.
This error is basically due to: Incorrect file or folder permissions.
Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to resolve Laravel related errors.
Tips to resolve Laravel error 403 ?
To fix this error in Laravel, apply the tips provide below.
1. Check the permissions and ownership
Whenever we receive this error our Support Experts initially check the permissions and ownerships of the files and folders.
And confirm that the permissions and the ownership of the files and folders are set correctly because this is one of the common reasons for this error to occur.
2. Checking the .htaccess file.
The .htaccess file also plays a major role in throwing the error message.
So, we check if there are any incorrect codes in it.
If so, then we either remove the code or rename the .htaccess file.
Here is the command that we run to rename the .htacess file:
mv .htaccess .htaccess-bck
3. Missing directives
Recently, one of our customers approached us with this error message on his Laravel website.
After fixing the permissions and checking the .htaccessfile, we checked for the virtual host configuration file httpd.conf placed in the path /etc/httpd/conf.d. We could see that the AllowOverride directive was missing in the configuration file.
Hence, the .htaccess file was not getting parsed by apache because the AllowOverride All directive was missing.
So, we added the below code in the virtual host configuration file:
<Directory /var/www/>
AllowOverride all
Require all granted
</Directory>
Then we restarted Apache using the command:
service httpd restart
After this, we cleared the cache and cookies.
Finally, we could see the website to be working well and the error 403 disappeared.
[Need urgent assistance in fixing Laravel errors? – We’ll help you. ]
Version
![]()
WARNING You’re browsing the documentation for an old version of Laravel.
Consider upgrading your project to Laravel 9.x.
Error Handling
- Introduction
- Configuration
-
The Exception Handler
- Report Method
- Render Method
- Reportable & Renderable Exceptions
-
HTTP Exceptions
- Custom HTTP Error Pages
Introduction
When you start a new Laravel project, error and exception handling is already configured for you. The AppExceptionsHandler
class is where all exceptions triggered by your application are logged and then rendered back to the user. We’ll dive deeper into this class throughout this documentation.
Configuration
The debug
option in your config/app.php
configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG
environment variable, which is stored in your .env
file.
For local development, you should set the APP_DEBUG
environment variable to true
. In your production environment, this value should always be false
. If the value is set to true
in production, you risk exposing sensitive configuration values to your application’s end users.
The Exception Handler
The Report Method
All exceptions are handled by the AppExceptionsHandler
class. This class contains two methods: report
and render
. We’ll examine each of these methods in detail. The report
method is used to log exceptions or send them to an external service like Flare, Bugsnag or Sentry. By default, the report
method passes the exception to the base class where the exception is logged. However, you are free to log exceptions however you wish.
For example, if you need to report different types of exceptions in different ways, you may use the PHP instanceof
comparison operator:
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Flare, Sentry, Bugsnag, etc.
*
* @param Throwable $exception
* @return void
*/
public function report(Throwable $exception)
{
if ($exception instanceof CustomException) {
//
}
parent::report($exception);
}
{tip} Instead of making a lot of
instanceof
checks in yourreport
method, consider using reportable exceptions
Global Log Context
If available, Laravel automatically adds the current user’s ID to every exception’s log message as contextual data. You may define your own global contextual data by overriding the context
method of your application’s AppExceptionsHandler
class. This information will be included in every exception’s log message written by your application:
/**
* Get the default context variables for logging.
*
* @return array
*/
protected function context()
{
return array_merge(parent::context(), [
'foo' => 'bar',
]);
}
The report
Helper
Sometimes you may need to report an exception but continue handling the current request. The report
helper function allows you to quickly report an exception using your exception handler’s report
method without rendering an error page:
public function isValid($value)
{
try {
// Validate the value...
} catch (Throwable $e) {
report($e);
return false;
}
}
Ignoring Exceptions By Type
The $dontReport
property of the exception handler contains an array of exception types that will not be logged. For example, exceptions resulting from 404 errors, as well as several other types of errors, are not written to your log files. You may add other exception types to this array as needed:
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
IlluminateAuthAuthenticationException::class,
IlluminateAuthAccessAuthorizationException::class,
SymfonyComponentHttpKernelExceptionHttpException::class,
IlluminateDatabaseEloquentModelNotFoundException::class,
IlluminateValidationValidationException::class,
];
The Render Method
The render
method is responsible for converting a given exception into an HTTP response that should be sent back to the browser. By default, the exception is passed to the base class which generates a response for you. However, you are free to check the exception type or return your own custom response:
/**
* Render an exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @param Throwable $exception
* @return IlluminateHttpResponse
*/
public function render($request, Throwable $exception)
{
if ($exception instanceof CustomException) {
return response()->view('errors.custom', [], 500);
}
return parent::render($request, $exception);
}
Reportable & Renderable Exceptions
Instead of type-checking exceptions in the exception handler’s report
and render
methods, you may define report
and render
methods directly on your custom exception. When these methods exist, they will be called automatically by the framework:
<?php
namespace AppExceptions;
use Exception;
class RenderException extends Exception
{
/**
* Report the exception.
*
* @return void
*/
public function report()
{
//
}
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
return response(...);
}
}
{tip} You may type-hint any required dependencies of the
report
method and they will automatically be injected into the method by Laravel’s service container.
HTTP Exceptions
Some exceptions describe HTTP error codes from the server. For example, this may be a «page not found» error (404), an «unauthorized error» (401) or even a developer generated 500 error. In order to generate such a response from anywhere in your application, you may use the abort
helper:
abort(404);
The abort
helper will immediately raise an exception which will be rendered by the exception handler. Optionally, you may provide the response text:
abort(403, 'Unauthorized action.');
Custom HTTP Error Pages
Laravel makes it easy to display custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a resources/views/errors/404.blade.php
. This file will be served on all 404 errors generated by your application. The views within this directory should be named to match the HTTP status code they correspond to. The HttpException
instance raised by the abort
function will be passed to the view as an $exception
variable:
<h2>{{ $exception->getMessage() }}</h2>
You may publish Laravel’s error page templates using the vendor:publish
Artisan command. Once the templates have been published, you may customize them to your liking:
php artisan vendor:publish --tag=laravel-errors
Laravel is primarily used for building custom web apps using PHP. It’s a web framework that handles many things that are annoying to build yourself, such as routing, templating HTML, and authentication.
Laravel is one of the best PHP web frameworks, but there are many other frameworks in different languages.
Laravel error 403 is one of the most common and annoying errors.
It mainly occurs due to improper permissions, ownerships, or any trouble with the .htaccess file and also missing directives.
The simple reason why we are seeing this error is that you are trying to access something you don’t have the permission for.
Throwing a 403 forbidden error is your website’s way of stating that you don’t have enough permissions to proceed further.
This error is basically due to: Incorrect file or folder permissions.
Here at Ibmi Media, as part of our Server Management Services, we regularly help our Customers to resolve Laravel related errors.
Tips to resolve Laravel error 403 ?
To fix this error in Laravel, apply the tips provide below.
1. Check the permissions and ownership
Whenever we receive this error our Support Experts initially check the permissions and ownerships of the files and folders.
And confirm that the permissions and the ownership of the files and folders are set correctly because this is one of the common reasons for this error to occur.
2. Checking the .htaccess file.
The .htaccess file also plays a major role in throwing the error message.
So, we check if there are any incorrect codes in it.
If so, then we either remove the code or rename the .htaccess file.
Here is the command that we run to rename the .htacess file:
mv .htaccess .htaccess-bck
3. Missing directives
Recently, one of our customers approached us with this error message on his Laravel website.
After fixing the permissions and checking the .htaccessfile, we checked for the virtual host configuration file httpd.conf placed in the path /etc/httpd/conf.d. We could see that the AllowOverride directive was missing in the configuration file.
Hence, the .htaccess file was not getting parsed by apache because the AllowOverride All directive was missing.
So, we added the below code in the virtual host configuration file:
<Directory /var/www/>
AllowOverride all
Require all granted
</Directory>
Then we restarted Apache using the command:
service httpd restart
After this, we cleared the cache and cookies.
Finally, we could see the website to be working well and the error 403 disappeared.
[Need urgent assistance in fixing Laravel errors? – We’ll help you. ]
#1 18.07.2014 19:27:56
Ошибка 403 из за отсутвия index.php
У меня вот такая проблема
Раньше работал на винде и использовал OpenServer
Потом поставил линукс и решил как истинный джедай сам собрать связку apache + php + mysql
Вроде как-то собрал.
Но когда я поставил Laravel при попытки захода на главную страницу мне выдается ошибка «403 — Forbidden»
В логе ошибок написанно следующеие
[Sun Jul 13 03:22:03.532705 2014] [autoindex:error] [pid 29735] [client 127.0.0.1:37242] AH01276: Cannot serve directory /home/volk/web/vi.dev/: No matching DirectoryIndex (index.php,index.html) found, and server-generated directory index forbidden by Options directive
Как я понял это ларавель жалуется на отсутствие индексных файлов
Но ведь когда я точно таким же способом устанавливал на laravel на OpenServer и там тоже не было индексных файлов, но всё равно все работало.
У меня когнитивный диссонанс, по логике вещей лаверль без index.php не должен был работать и на OpenServer.
Конфигурация виртуального хоста выглядит вот так.
<VirtualHost *:80>
ServerName vi.dev
ServerAlias www.vi.dev
DocumentRoot /home/volk/web/vi.dev
ServerAdmin webmaster@localhost
ErrorLog ${APACHE_LOG_DIR}/error.log
<Directory "/home/volk/web/vi.dev">
Require all granted
DirectoryIndex index.php index.html
</Directory>
</VirtualHost>
Подскажите что за колдовская сила заставляет ларваель работать без index.php в корневой папке сайта?
И каким образом сделать чтобы он заработал и у меня?
#2 18.07.2014 19:38:40
Re: Ошибка 403 из за отсутвия index.php
- Как я понял это ларавель жалуется на отсутствие индексных файлов
Это стандартная ошибка (на самом деле предупреждение) Apache, говорит о том, что в папке, куда ты зашёл через браузер без указания файла (http://foo/folder/), нет index.html/php, поэтому он не может что-либо отобразить.
- там тоже не было индексных файлов
Как же не было, public/index.php не в счёт?
- DocumentRoot /home/volk/web/vi.dev
Неверно — у тебя корень сайта — корень фреймворка, а это должна быть папка public. Именно там находится Laravel-овский index.php. <Directory>, кстати, лишняя — обычно эти настройки уже и так заданы по умолчанию.
#3 19.07.2014 19:48:16
Re: Ошибка 403 из за отсутвия index.php
Спасибо, я использовал вот такую конифигурацю
<VirtualHost *:80>
ServerName vi.dev
ServerAlias www.vi.dev
DocumentRoot /home/volk/web/vi.dev/public
ServerAdmin me@localhost
<Directory "/home/volk/web/vi.dev">
Require all granted
</Directory>
</VirtualHost>
и кажется проблема с 403 исчезла. Теперь вместо неё сообщение Mcrypt PHP extension required.
сейчас буду разбираться как приделать mcrypt к php.
P.S.
Directory все таки важна, так как по умолчанию apache хочет чтобы сайты были вот тут /var/www/html, а я хочу чтобы они лежали в ~/web (созданная мной папка), чтобы каждый раз не заморачиваться с sudo при работе с сайтами.
#4 28.04.2016 12:14:00
Re: Ошибка 403 из за отсутвия index.php
Да, но что делать, если это обычный хост и нет доступа к конфигу апача?
#5 01.05.2016 14:10:08
Re: Ошибка 403 из за отсутвия index.php
caper87 пишет:
Да, но что делать, если это обычный хост и нет доступа к конфигу апача?
1. Заказать VPS/VDS.
2. Не использовать фреймворк.
3. Залить Laravel в корень (туда, где лежит public_html, htdocs или www) и попробовать поставить симлинк между public_html и public.
#6 02.05.2016 23:13:04
Re: Ошибка 403 из за отсутвия index.php
Понял, значит пряморукого решения с хостом нет. Печально.
Благодарю за ответ
#7 11.05.2016 19:02:07
Re: Ошибка 403 из за отсутвия index.php
Пряморукое решение есть — просто настроить Apache так, как вам нужно. Все эти директории (www, html и т.п.) настраиваются в конфиге. Так что смело изучайте конфиг и документацию.
Обработка ошибок
- Введение
- Настройка
-
Обработчик исключений
- Метод Report
- Метод Render
- Reportable и Renderable исключения
-
HTTP-исключения
- Пользовательские страницы HTTP-ошибок
Introduction
В Laravel обработка исключений ведётся классом AppExceptionsHandler
. Возникшие исключения логируются и при необходимости показываются пользователю. Давайте рассмотрим работу этого класса поподробнее.
Настройка
Опция debug
в config/app.php
определяет, показывать ли информацию об ошибке пользователю. По умолчанию значение берётся из APP_DEBUG
, определённого в .env
файле.
В процессе разработки APP_DEBUG
удобно установить в true
. На сервере, в продакшне, это значение логично ставить в false
, чтобы в сообщении об ошибке случайно не показать чувствительные для безопасности проекта вещи.
Обработчик исключений
Все исключения обрабатываются классом AppExceptionsHandler
. Этот класс содержит два метода: report
и render
. Рассмотрим каждый из них подробнее.
Метод Report
Метод report
используется для логирование исключений или для отправки их во внешний сервис, такой как Flare, Bugsnag или Sentry. По умолчанию метод report
просто передаёт исключение в базовую реализацию родительского класса, где это происходит запись исключения в лог-файл. Но вы можете регистрировать исключения как пожелаете.
Например, если вам необходимо сообщать о различных типах исключений разными способами, вы можете использовать оператор сравнения PHP instanceof
:
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Flare, Sentry, Bugsnag, etc.
*
* @param Exception $exception
* @return void
*/
public function report(Exception $exception)
{
if ($exception instanceof CustomException) {
//
}
parent::report($exception);
}
Вместо проверок
instanceof
можно использовать reportable exceptions.
Глобальный контекст для логирования
Если доступно, Laravel автоматически добавляет id текущего пользователя к каждому сообщению журнала исключений в качестве контекстных данных. Вы можете определить свои собственные глобальные контекстные данные, переопределив метод context
класса AppExceptionsHandler
. Эта информация будет включена в лог каждого исключения:
/**
* Get the default context variables for logging.
*
* @return array
*/
protected function context()
{
return array_merge(parent::context(), [
'foo' => 'bar',
]);
}
Хелпер report
Иногда вам надо зафиксировать наличие исключения, но продолжить обрабатывать запрос. Хелпер report
поможет это сделать, без рендеринга страницы ошибки:
public function isValid($value)
{
try {
// Validate the value...
} catch (Exception $e) {
report($e);
return false;
}
}
Игнорирование исключений по типу
Свойство $dontReport
класса AppExceptionsHandler
содержит массив типов исключений, которые не будут логироваться. Например, в лог-файлы не записываются исключения ошибок 404, а также некоторые другие типы ошибок. При необходимости в этот массив можно добавить и другие типы исключений:
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
IlluminateAuthAuthenticationException::class,
IlluminateAuthAccessAuthorizationException::class,
SymfonyComponentHttpKernelExceptionHttpException::class,
IlluminateDatabaseEloquentModelNotFoundException::class,
IlluminateValidationValidationException::class,
];
Метод Render
Метод render
отвечает за преобразование заданного исключения в ответ HTTP, который должен быть отправлен обратно в браузер. По умолчанию исключение передается базовому классу, который генерирует ответ. Однако, вы можете проверить тип исключения или вернуть свой собственный пользовательский ответ:
/**
* Render an exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @param Exception $exception
* @return IlluminateHttpResponse
*/
public function render($request, Exception $exception)
{
if ($exception instanceof CustomException) {
return response()->view('errors.custom', [], 500);
}
return parent::render($request, $exception);
}
Reportable и Renderable исключения
Вместо того, чтобы проверять в AppExceptionsHandler
, как именно надо среагировать на исключение по его типу, отправить просто репорт или http-ответ, вы можете добавить в свои исключения методы report
или render
— и фреймворк будет вызывать их автоматически.
<?php
namespace AppExceptions;
use Exception;
class RenderException extends Exception
{
/**
* Report the exception.
*
* @return void
*/
public function report()
{
//
}
/**
* Render the exception into an HTTP response.
*
* @param IlluminateHttpRequest $request
* @return IlluminateHttpResponse
*/
public function render($request)
{
return response(...);
}
}
Фреймворк также позволяет добавить зависимости в аргументы метода
report
— они будут автоматически подгружены при помощи сервис-контейнера
HTTP-исключения
Некоторые исключения описывают коды HTTP-ошибок от сервера. Например, это может быть ошибка «страница не найдена» (404), «ошибка авторизации» (401) или даже сгенерированная разработчиком ошибка 500. Для возврата такого отклика из любого места в приложении можете использовать хелпер abort
:
abort(404);
Хелпер abort
немедленно создаёт исключение, которое будет отрисовано обработчиком исключений. Или вы можете предоставить такой отклик:
abort(403, 'Unauthorized action.');
Пользовательские страницы HTTP-ошибок
Для того, чтобы сделать свою страницу для показа в случае возникновения ошибки 404 — создайте файл resources/views/errors/404.blade.php
. Со страницами по ошибкам с другими кодами — действия аналогичны, располагайте blade-файлы с кодом ошибки в названии в папке resources/views/errors
. Исключение будет доступно в переменной $exception
:
<h2>{{ $exception->getMessage() }}</h2>
Чтобы опубликовать в вашем приложении дефолтные страницы ошибок Laravel (например, для того, чтобы их изменить), воспользуйтесь artisan-командой vendor::publish
с указанным тэгом:
php artisan vendor:publish --tag=laravel-errors