Ошибка 403 доступ запрещен в apache

Update October 2016

4 years ago, since this answer is used as a reference by many, and while I learned a lot from security perspective during these years,
I feel I am responsible to clarify some important notes, and I’ve update my answer accordingly.

The original answer is correct but not safe for some production environments,
in addition I would like to explain some issues that you might fall into while setting up your environment.

If you are looking for a quick solution and SECURITY IS NOT A MATTER, i.e development env, skip and read the original answer instead

Many scenarios can lead to 403 Forbidden:


A. Directory Indexes (from mod_autoindex.c)

When you access a directory and there is no default file found in this directory
AND Apache Options Indexes is not enabled for this directory.

A.1. DirectoryIndex option example

DirectoryIndex index.html default.php welcome.php

A.2. Options Indexes option

If set, Apache will list the directory content if no default file found (from the above 👆🏻 option)

If none of the conditions above is satisfied

You will receive a 403 Forbidden

Recommendations

  • You should not allow directory listing unless REALLY needed.
  • Restrict the default index DirectoryIndex to the minimum.
  • If you want to modify, restrict the modification to the needed directory ONLY, for instance, use .htaccess files, or put your modification inside the <Directory /my/directory> directive

B. deny,allow directives (Apache 2.2)

Mentioned by @Radu, @Simon A. Eugster in the comments
You request is denied, blacklisted or whitelisted by those directives.

I will not post a full explanation, but I think some examples may help you understand,
in short remember this rule:

IF MATCHED BY BOTH, THE LAST DIRECTIVE IS THE ONE THAT WILL WIN

Order allow,deny

Deny will win if matched by both directives (even if an allow directive is written after the deny in the conf)

Order deny,allow

allow will win if matched by both directives

Example 1

Order allow,deny
Allow from localhost mydomain.example

Only localhost and *.mydomain.example can access this, all other hosts are denied

Example 2

Order allow,deny
Deny from evil.example
Allow from safe.evil.example # <-- has no effect since this will be evaluated first

All requests are denied, the last line may trick you, but remember that if matched by both the last win rule (here Deny is the last), same as written:

Order allow,deny
Allow from safe.evil.example
Deny from evil.example # <-- will override the previous one

Example 4

Order deny,allow
Allow from site.example
Deny from untrusted.site.example # <-- has no effect since this will be matched by the above `Allow` directive

Requests are accepted from all hosts

Example 4: typical for public sites (allow unless blacklisted)

Order allow,deny
Allow from all
Deny from hacker1.example
Deny from hacker2.example

Example 5: typical for intranet and secure sites (deny unless whitelisted)

Order deny,allow
Deny from all
Allow from mypc.localdomain
Allow from managment.localdomain

C. Require directive (Apache 2.4)

Apache 2.4 use a new module called mod_authz_host

Require all granted => Allow all requests

Require all denied => Deny all requests

Require host safe.example => Only from safe.example are allowed


D. Files permissions

One thing that most people do it wrong is configuring files permissions,

The GOLDEN RULE is

STARTS WITH NO PERMISSION AND ADD AS PER YOUR NEED

In Linux:

  • Directories should have the Execute permission

  • Files should have the Read permission

  • YES, you are right DO NOT ADD Execute permission for files

for instance, I use this script to setup the folders permissions

# setting permissions for /var/www/mysite.example

# read permission ONLY for the owner
chmod -R /var/www/mysite.example 400

# add execute for folders only
find /var/www/mysite.example -type d -exec chmod -R u+x {} ;

# allow file uploads
chmod -R /var/www/mysite.example/public/uploads u+w

# allow log writing to this folder
chmod -R /var/www/mysite.example/logs/

I posted this code as an example, setup may vary in other situations



Original Answer

I faced the same issue, but I solved it by setting the options directive either in the global directory setting in the httpd.conf or in the specific directory block in httpd-vhosts.conf:

Options Indexes FollowSymLinks Includes ExecCGI

By default, your global directory settings is (httpd.conf line ~188):

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order deny,allow
    Allow from all
</Directory>

set the options to:
Options Indexes FollowSymLinks Includes ExecCGI

Finally, it should look like:

<Directory />
    #Options FollowSymLinks
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Order deny,allow
    Allow from all
</Directory>

Also try changing Order deny,allow and Allow from all lines by Require all granted.

Appendix

Directory Indexes source code (some code remove for brevity)

if (allow_opts & OPT_INDEXES) {
     return index_directory(r, d);
} else {
        const char *index_names = apr_table_get(r->notes, "dir-index-names");

        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01276)
                      "Cannot serve directory %s: No matching DirectoryIndex (%s) found, and "
                      "server-generated directory index forbidden by "
                      "Options directive",
                       r->filename,
                       index_names ? index_names : "none");
        return HTTP_FORBIDDEN;
    }

Introduction

Apache is a popular open-source app for running web servers, owing to its reliability and stability. Despite its ease of use, it’s not uncommon to encounter a ‘403 Forbidden’ error after setting up a website using Apache.

In this tutorial, we will go over potential causes of the Apache ‘403 Forbidden’ error and different ways you can fix it.

Apache 403 forbidden: reasons and how to fix it

Prerequisites

  • A user account with root or sudo privileges
  • Access to the command line terminal
  • An installed version of Apache web server

Apache 403 Forbidden: Effects and Possible Causes

The Apache ‘403 Forbidden’ error appears when you try to load a web page with restricted access. Depending on your browser and the website in question, there are different versions of the 403 error message:

  • Forbidden
  • Error 403
  • HTTP Error 403.14 – Forbidden
  • 403 Forbidden
  • HTTP 403
  • Forbidden: You don’t have permission to access the site using this server
  • Error 403 – Forbidden
  • HTTP Error 403 – Forbidden
Example of an Apache 403 forbidden error message.

There are several potential reasons why the Apache 403 error occurs:

  • The first option is a permission error in the webroot directory, where users don’t have access to website files.
  • The second possible reason for a 403 error is missing or incorrect settings in the Apache configuration files.
  • Finally, failing to set up a default directory index also triggers a 403 error message in Apache.

How to Fix ‘403 Forbidden’ in Apache

If you have come across an Apache ‘403 Forbidden’ message, there are several ways to fix it:

Method 1: Setting File Permissions and Ownership

If you suspect the cause of the 403 error to be incorrect file permissions, use:

sudo chmod -R 775 /path/to/webroot/directory

The chmod command sets the execute permission for the webroot directory and read permission for the index.html file.

To change directory ownership, use:

sudo chown -R user:group /path/to/webroot/directory

Where:

  • user is the user account with root privileges on your web server.
  • group is www-data or apache.

Restart the Apache web server for the changes to take effect.

If you are working with Ubuntu, use the following command to restart Apache:

sudo systemctl restart apache2

If you are working with Centos, use:

sudo systemctl restart httpd

Method 2: Setting Apache Directives

It is possible that the proper require directive is not configured and restricts access to resources. To fix it:

1. Access Apache’s main configuration file. For Ubuntu, use:

sudo nano /etc/apache2/apache2.conf

For Centos, use:

sudo nano /etc/httpd/httpd.conf

2. Once you open the configuration file, scroll down to the following section:

Apache main configuration file

3. If the final line in the <Directory /var/www/> section contains Require all denied, change it to Require all granted.

4. Press Ctrl+X and then Y to save changes to the Apache configuration file.

5. Restart the Apache web server for the changes to take effect. For Ubuntu, use:

sudo systemctl restart apache2

For Centos, use:

sudo systemctl restart httpd

Method 3: Adding a Default Directory Index

When a user visits a URL that requests a directory, the web server looks for a file in the given directory. If the file or any similar files are not found, and directory index listings are disabled, the web server displays the ‘403 Forbidden’ error message.

To fix the issue, add a default directory index.

1. Access Apache’s main configuration file by using:

sudo nano /etc/apache2/apache2.conf

2. Scroll down to find out the default index file name:

DirectoryIndex index.html index.cgi index.pl index.php index.xhtml

3. Make sure there is a file in the webroot folder with this name and upload it if it’s missing.

Conclusion

After following this tutorial, you should be able to determine the cause of an Apache ‘403 Forbidden’ error and fix any issues you may find.

If you want to find out more about 403 forbidden error, read our article 403 forbidden error — what is it and how to fix it.

Apache web server is one of the most popular and widely used open-source web servers thanks to its stability and reliability. The web server commands a huge market, especially in the web hosting platforms.

Be that as it may, you may get a “Forbidden – You don’t have permission to access / on this server” error on your browser after setting up your website. It’s quite a common error and a good chunk of users have experienced it while testing their site. So what is this error?

Demystifying the Forbidden Error

Also referred to as the 403 Forbidden error, Apache’s ‘Forbidden Error’ is an error that is displayed on a web page when you are attempting to access a website that’s restricted or forbidden. It’s usually splashed on the browser as shown.

Apache Forbidden Error

Apache Forbidden Error

Additionally, the error can manifest in several ways on the browser as indicated below:

  • HTTP Error 403 – Forbidden
  • Forbidden: You don’t have permission to access [directory] on this server
  • 403 Forbidden
  • Access Denied You don’t have permission to access
  • 403 forbidden requests forbidden by administrative rules

So what causes such errors?

The ‘403 Forbidden Error‘ occurs due to the following main reasons:

1. Incorrect File / Directory Permissions

This error can be triggered due to incorrect file/folder permissions on the webroot directory. If the default file permissions are not adjusted to grant users access to the website files, then the chances of this error popping on a web browser are high.

2. Misconfiguration of the Apache Configuration Files

This error can also be attributed to a misconfiguration of one of the Apache configuration files. It could be an incorrect parameter that has been included or missing directives in the configuration file.

Fixing the ‘403 Forbidden Error’

If you have encountered this error, here are a few steps that you can take to remedy this.

1. Adjust file permissions & ownership of the webroot directory

Incorrect file permissions & directory ownership are known to restrict access to website files. So, firstly, be sure to assign the file permissions recursively to the webroot directory as shown.

The webroot directory should always have EXECUTE permissions and the index.html file should have READ permissions.

$ sudo chmod -R 775 /path/to/webroot/directory

Additionally, adjust the directory ownership as shown:

$ sudo chown -R user:group /path/to/webroot/directory

Where the user is the regular logged-in user and the group is www-data or apache.

Finally, reload or restart the Apache webserver for the changes to take effect.

$ sudo systemctl restart apache2
OR
$ sudo systemctl restart httpd

If this does not resolve the issue, proceed to the next step:

2. Adjust directives in Apache main configuration file

If you are on Debian-based Linux, in Apache’s main configuration file /etc/apache2/apache2.conf, ensure that you have this block of code:

<Directory />
        Options FollowSymLinks
        AllowOverride None
        Require all denied
</Directory>

<Directory /usr/share>
        AllowOverride None
        Require all granted
</Directory>

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

Save and exit and thereafter, restart the Apache.

If you are running Apache on RHEL-based distributions / CentOS systems, ensure that you relax access to the /var/www directory in the /etc/httpd/conf/httpd.conf main Apache configuration file.

<Directory "/var/www">
    AllowOverride None
    Require all granted
</Directory>

Then save all the changes and reload Apache.

If after trying all these steps you are still getting the error, then please check the configuration of your virtual host files. We have detailed articles on how you can configure the Apache Virtual host file on:

  • How to Install Apache with Virtual Hosts on Debian
  • How to Configure Apache Virtual Hosts on Rocky Linux
  • How to Install Apache with Virtual Host on CentOS

I hope that the steps provided have helped you clear the 403 error.

На чтение 3 мин Опубликовано 19.07.2020

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

Веб-сервер управляет огромным рынком, особенно на платформах веб-хостинга.

Как бы то ни было, вы можете получить ошибку «Forbidden – You don’t have permission to access / on this server» в вашем браузере после настройки вашего веб-сайта.

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

Так в чем же эта ошибка?

Также называемая «ошибка 403», эта такая ошибка в Apache , которая отображается на веб-странице, когда вы пытаетесь получить доступ к веб-сайту с ограниченным или запрещенным доступом.

Кроме того, ошибка может отображаться по разному:

  • HTTP Error 403 – Forbidden
  • Forbidden: You don’t have permission to access [directory] on this server
  • 403 Forbidden
  • Access Denied You don’t have permission to access
  • 403 forbidden request forbidden by administrative rules

Содержание

  1. Так что вызывает такие ошибки?
  2. 1. Неправильные права доступа к файлам / каталогам
  3. 2. Неправильная настройка файлов конфигурации Apache
  4. Фиксим ‘403 Forbidden Error’
  5. 1. Настройте права доступа к файлам и владение каталогом webroot
  6. 2. Настройте директивы в главном конфигурационном файле Apache

Так что вызывает такие ошибки?

‘403 ошибка‘ возникает по следующим основным причинам:

1. Неправильные права доступа к файлам / каталогам

Эта ошибка может быть вызвана из-за неправильных прав доступа к файлам/папкам в каталоге webroot.

Если права доступа к файлам по умолчанию не настроены для предоставления пользователям доступа к файлам веб-сайта, то вероятность появления этой ошибки в веб-браузере высока.

2. Неправильная настройка файлов конфигурации Apache

Эта ошибка также может быть связана с неправильной настройкой одного из файлов конфигурации Apache.

Это может быть неверный параметр, который был включен по ошибке, или отсутствующие директивы в файле конфигурации.

Фиксим ‘403 Forbidden Error’

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

1. Настройте права доступа к файлам и владение каталогом webroot

Известно, что неправильные права доступа к файлам и владение каталогами ограничивают доступ к файлам сайта.

Поэтому, во-первых, убедитесь, что права доступа к файлам рекурсивно назначены каталогу webroot, как показано далее.

Каталог webroot всегда должен иметь разрешения EXECUTE, а файл index.html должен иметь разрешения READ.

$ sudo chmod -R 775 /path/to/webroot/directory

Кроме того, настройте владельца каталога, как показано далее:

$ sudo chown -R user:group /path/to/webroot/directory

Где user является обычным вошедшим в систему пользователем, а группа – www-data или apache.

Наконец, перезапустите веб-сервер Apache, чтобы изменения вступили в силу.

$ sudo systemctl restart apache2

Если это не решает проблему, перейдите к следующему шагу:

2. Настройте директивы в главном конфигурационном файле Apache

Убедитесь, что в главном конфигурационном файле Apache /etc/apache2/apache2.conf  у вас есть этот блок кода:

<Directory />
        Options FollowSymLinks
        AllowOverride None
        Require all denied
</Directory>

<Directory /usr/share>
        AllowOverride None
        Require all granted
</Directory>

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

Сохраните и выйдите, а затем перезапустите Apache.

Если вы используете Apache в системах RHEL / CentOS, убедитесь, что вы ослабили доступ к каталогу /var/www в главном файле конфигурации Apache /etc/httpd/conf/httpd.conf.

<Directory "/var/www">
    AllowOverride None
    Require all granted
</Directory>

Затем сохраните все изменения и перезагрузите Apache.

Пожалуйста, не спамьте и никого не оскорбляйте.

Это поле для комментариев, а не спамбокс.

Рекламные ссылки не индексируются!

Update October 2016

4 years ago, since this answer is used as a reference by many, and while I learned a lot from security perspective during these years,
I feel I am responsible to clarify some important notes, and I’ve update my answer accordingly.

The original answer is correct but not safe for some production environments,
in addition I would like to explain some issues that you might fall into while setting up your environment.

If you are looking for a quick solution and SECURITY IS NOT A MATTER, i.e development env, skip and read the original answer instead

Many scenarios can lead to 403 Forbidden:


A. Directory Indexes (from mod_autoindex.c)

When you access a directory and there is no default file found in this directory
AND Apache Options Indexes is not enabled for this directory.

A.1. DirectoryIndex option example

DirectoryIndex index.html default.php welcome.php

A.2. Options Indexes option

If set, Apache will list the directory content if no default file found (from the above 👆🏻 option)

If none of the conditions above is satisfied

You will receive a 403 Forbidden

Recommendations

  • You should not allow directory listing unless REALLY needed.
  • Restrict the default index DirectoryIndex to the minimum.
  • If you want to modify, restrict the modification to the needed directory ONLY, for instance, use .htaccess files, or put your modification inside the <Directory /my/directory> directive

B. deny,allow directives (Apache 2.2)

Mentioned by @Radu, @Simon A. Eugster in the comments
You request is denied, blacklisted or whitelisted by those directives.

I will not post a full explanation, but I think some examples may help you understand,
in short remember this rule:

IF MATCHED BY BOTH, THE LAST DIRECTIVE IS THE ONE THAT WILL WIN

Order allow,deny

Deny will win if matched by both directives (even if an allow directive is written after the deny in the conf)

Order deny,allow

allow will win if matched by both directives

Example 1

Order allow,deny
Allow from localhost mydomain.example

Only localhost and *.mydomain.example can access this, all other hosts are denied

Example 2

Order allow,deny
Deny from evil.example
Allow from safe.evil.example # <-- has no effect since this will be evaluated first

All requests are denied, the last line may trick you, but remember that if matched by both the last win rule (here Deny is the last), same as written:

Order allow,deny
Allow from safe.evil.example
Deny from evil.example # <-- will override the previous one

Example 4

Order deny,allow
Allow from site.example
Deny from untrusted.site.example # <-- has no effect since this will be matched by the above `Allow` directive

Requests are accepted from all hosts

Example 4: typical for public sites (allow unless blacklisted)

Order allow,deny
Allow from all
Deny from hacker1.example
Deny from hacker2.example

Example 5: typical for intranet and secure sites (deny unless whitelisted)

Order deny,allow
Deny from all
Allow from mypc.localdomain
Allow from managment.localdomain

C. Require directive (Apache 2.4)

Apache 2.4 use a new module called mod_authz_host

Require all granted => Allow all requests

Require all denied => Deny all requests

Require host safe.example => Only from safe.example are allowed


D. Files permissions

One thing that most people do it wrong is configuring files permissions,

The GOLDEN RULE is

STARTS WITH NO PERMISSION AND ADD AS PER YOUR NEED

In Linux:

  • Directories should have the Execute permission

  • Files should have the Read permission

  • YES, you are right DO NOT ADD Execute permission for files

for instance, I use this script to setup the folders permissions

# setting permissions for /var/www/mysite.example

# read permission ONLY for the owner
chmod -R /var/www/mysite.example 400

# add execute for folders only
find /var/www/mysite.example -type d -exec chmod -R u+x {} ;

# allow file uploads
chmod -R /var/www/mysite.example/public/uploads u+w

# allow log writing to this folder
chmod -R /var/www/mysite.example/logs/

I posted this code as an example, setup may vary in other situations



Original Answer

I faced the same issue, but I solved it by setting the options directive either in the global directory setting in the httpd.conf or in the specific directory block in httpd-vhosts.conf:

Options Indexes FollowSymLinks Includes ExecCGI

By default, your global directory settings is (httpd.conf line ~188):

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order deny,allow
    Allow from all
</Directory>

set the options to:
Options Indexes FollowSymLinks Includes ExecCGI

Finally, it should look like:

<Directory />
    #Options FollowSymLinks
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Order deny,allow
    Allow from all
</Directory>

Also try changing Order deny,allow and Allow from all lines by Require all granted.

Appendix

Directory Indexes source code (some code remove for brevity)

if (allow_opts & OPT_INDEXES) {
     return index_directory(r, d);
} else {
        const char *index_names = apr_table_get(r->notes, "dir-index-names");

        ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(01276)
                      "Cannot serve directory %s: No matching DirectoryIndex (%s) found, and "
                      "server-generated directory index forbidden by "
                      "Options directive",
                       r->filename,
                       index_names ? index_names : "none");
        return HTTP_FORBIDDEN;
    }

Понравилась статья? Поделить с друзьями:
  • Ошибка 403 forbidden на сайте как исправить
  • Ошибка 403 forbidden доступ запрещен
  • Ошибка 403 forbidden в google
  • Ошибка 403 forbidden access denied
  • Ошибка 403 access denied на сайте