403 forbidden apache как исправить

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.

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;
    }

Did you just try to access your site only to be hit by some message telling you something is “Forbidden” or that you don’t have permission to access something on your site? If so, you’ve likely run into the 403 Forbidden error.

Seeing an error on your site can be frustrating and deflating, which is why we’ve created this detailed guide to help you fix the 403 Forbidden error and get your site functioning again as quickly as possible.

Let’s get started without any further introduction because we’re sure you just want to fix your site!

Check Out Our Video Guide on Fixing a 403 Forbidden Error on Your Site

What is the 403 Forbidden Error?

The 403 Forbidden error indicates that the server understands the request but can’t provide additional access. This means that the web page you’re trying to open in your browser is a resource that you’re not allowed to access.

Error Code 403
Error Type Authentication error
Error Variations Forbidden – You don’t have permission to access / on this server
403 – Forbidden: Access is denied
Error 403 – Forbidden
403 – Forbidden Error – You are not allowed to access this address
403 Forbidden – nginx
Error Causes Corrupt .htaccess file
Incorrect file permissions
Plugin issues

Like many other common errors, the 403 Forbidden error is an HTTP status code that a web server uses to communicate with your web browser.

403 forbidden error in Chrome

403 forbidden error in Chrome

Quick background on HTTP status codes – whenever you connect to a website with your browser, the web server responds with something called an HTTP header. Usually, this all happens behind the scenes because everything is working normally (that’s a 200 status code, in case you were wondering).

However, if something goes wrong, the server will respond back with a different numbered HTTP status code. While these numbers are frustrating to encounter, they’re actually quite important because they help you diagnose exactly what’s going wrong on your site.

The 403 Forbidden error means that your web server understands the request that the client (i.e. your browser) is making, but the server will not fulfill it.

In more human-friendly terms, it basically means that your server knows exactly what you want to do, it just won’t let you do it because you don’t have the proper permissions for some reason. It’s kind of like you’re trying to get into a private event, but your name got accidentally removed from the guestlist for some reason.

Other HTTP status codes mean different things. We’ve written guides on fixing issues with:

  • 404 not found errors
  • 500 internal server errors
  • 502 bad gateway errors
  • 504 gateway timeout errors.

What Causes the 403 Forbidden Error?

The two most likely causes of the 403 Forbidden Error are:

  1. Corrupt .htaccess file
  2. Incorrect file permissions

It’s also possible that you’re seeing the error because of an issue with a plugin that you’re using at your site. In this article, we’ll show you how to troubleshoot all of these potential issues.

403 Forbidden Error Variations

Like many other HTTP status codes, there are a lot of different variations for how this error code presents itself.

Here are some common variations that you might come across:

  • “Forbidden – You don’t have permission to access / on this server”
  • “403 – Forbidden: Access is denied”
  • “Error 403 – Forbidden”
  • “403 – Forbidden Error – You are not allowed to access this address”
  • “403 Forbidden – nginx”
  • “HTTP Error 403 – Forbidden – You do not have permission to access the document or program you requested”
  • “403 Forbidden – Access to this resource on the server is denied”
  • “403. That’s an error. Your client does not have permission to get URL / from this server”
  • “You are not authorized to view this page”
  • “It appears you don’t have permission to access this page.”

If you’re on an Nginx server, it will look like this below. Basically, if you see any mention of “forbidden” or “not allowed to access”, you’re probably dealing with a 403 Forbidden error.

What the 403 Forbidden Error looks like at Kinsta

What the 403 Forbidden Error looks like at Kinsta

How to Fix a 403 Forbidden Error?

To help you fix the 403 Forbidden Error on your site, we’ll cover nine separate troubleshooting steps in detail:

1. Refresh the Page and Double Check the Address

Sometimes the simplest solutions are the only ones capable of solving complex problems.

So try to refresh the page you are not able to access. The 403 error is often temporary, so maybe you’ll get lucky.

We also recommend checking that the URL is spelled correctly. If the address you are trying to access is a directory and not a web page, there is a chance that you will encounter a 403 error. (example: www.kinsta.com/wp-content/uploads/2023/05/)

2. Clear Your Browser Cache

Another very handy solution is to clear your browser’s cache.

Cache is very useful to help us see a website faster, but sometimes some mismatch can happen between the real version of a page and its cached version.

Check below some tips on how to clear cache in various browsers:

  • How to Force Refresh a Single Page for All Browsers
  • How to Clear Browser Cache for Google Chrome
  • How to Clear Browser Cache for Mozilla Firefox
  • How to Clear Browser Cache for Safari
  • How to Clear Browser Cache for Internet Explorer
  • How to Clear Browser Cache for Microsoft Edge
  • How to Clear Browser Cache for Opera

3. Modify Your File Permissions

Each folder and file on your site’s server has its own unique file permissions that control who can:

  • Read – see the data in the file/view the contents of a folder.
  • Write – modify the file/add or delete files inside a folder
  • Execute – run the file and/or execute it as a script/access a folder and perform functions and commands.

These permissions are indicated by a 3-digit number, with each digit indicating the level of permission for each of the 3 categories above.

Normally, these permissions just “work” for your site.

However, if something gets messed up with the file permissions at your site, it can cause the 403 Forbidden error.

To view and modify your site’s file permissions, you’ll need to connect via FTP/SFTP. Here’s how to use SFTP if you’re hosting at Kinsta.

For the screenshots in the tutorial below, we’ll be using the free FileZilla FTP program.

The basic principles will apply to any FTP program, though – you’ll just need to apply them to a different interface.

Once you’re connected to your server, you can view a file or folder’s permissions by right-clicking on it:

View file permissions in FileZilla

View file permissions in FileZilla

Of course, manually checking the permissions for each file or folder isn’t really an option.

Instead, you can automatically apply file permissions to all the files or folders inside of a folder.

According to the WordPress Codex, the ideal file permissions for WordPress are:

  • Files  – 644 or 640
  • Directories – 755 or 750

One exception is that your wp-config.php file should be 440 or 400.

To set these permissions, right-click on the folder that contains your site (the folder name is public at Kinsta). Then, choose File Attributes:

Bulk edit file permissions in FileZilla

Bulk edit file permissions in FileZilla

Enter 755 or 750 in the Numeric value box. Then, choose Recurse into subdirectories and Apply to directories only:

File permissions for WordPress directories

File permissions for WordPress directories

Once you’ve applied the correct permissions for directories, you’ll repeat the process for files. Only this time:

  • Enter 644 or 640 in the Numeric value box
  • Choose Recurse into subdirectories
  • Choose Apply to files only

File permissions for WordPress files

File permissions for WordPress files

To finish the process, you just need to manually adjust the permissions for your wp-config.php file to make them 440 or 400:

File permissions for wp-config.php file

File permissions for wp-config.php file

If file permissions issues were causing the 403 Forbidden Error, your site should now start working again.

4. Delete and Restore the .htaccess File

Kinsta uses the NGINX web server, so this potential issue doesn’t apply if you’re hosting your site at Kinsta because Kinsta sites do not have a .htaccess file.

However, if you’re hosting elsewhere and your host uses the Apache web server, one common cause of the 403 Forbidden error is a problem in your site’s .htaccess file.

The .htaccess file is a basic configuration file used by the Apache web server. You can use it to set up redirects, restrict access to all or some of your site, etc.

Because it’s so powerful, even if a little mistake can cause a big issue, like the 403 Forbidden error.

Rather than trying to troubleshoot the .htaccess file itself, a simpler solution is to just force WordPress to generate a new, clean .htaccess file.

To do that:

  • Connect to your server via FTP
  • Find the .htaccess file in your root folder
  • Download a copy of the file to your computer (it’s always a good idea to have a backup just in case)
  • Delete the .htaccess file from your server after you have a safe backup copy on your local computer

Delete the .htaccess file

Delete the .htaccess file

Now, you should be able to access your WordPress site if your .htaccess file was the issue.

To force WordPress to generate a new, clean .htaccess file:

  • Go to Settings → Permalinks in your dashboard
  • Click Save Changes at the bottom of the page (you do not need to make any changes – just click the button)

How to generate a new, clean .htaccess file

How to generate a new, clean .htaccess file

And that’s it – WordPress will now generate a new .htaccess file for you.

5. Deactivate and then Reactivate Your Plugins

If neither your site’s file permissions nor .htaccess file are the problems, the next place to look is your WordPress plugins. It could be a bug in a plugin or a compatibility issue between different plugins.

No matter what the issue is, the easiest way to find the problematic plugin is with a little trial and error. Specifically, you’ll need to deactivate all of your plugins and then reactivate them one by one until you find the culprit.

If you can still access your dashboard, you can perform this process from the normal Plugins area.

If you cannot access your dashboard, you’ll instead need to connect to your WordPress site’s server via FTP/SFTP (here’s how to connect via SFTP at Kinsta).

Once you’re connected to your server via FTP:

  1. Browse to the wp-content folder
  2. Find the plugins folder inside of the wp-content folder
  3. Right-click on the plugins folder and choose Rename
  4. Change the name of the folder. You can name it anything different, but we recommend something like plugins-disabled to make it easy to remember.

Rename the plugins folder

Rename the plugins folder

By renaming the folder, you’ve effectively disabled all the plugins at your site.

Now, try accessing your site again. If your site is working, you know that one of your plugins is causing the 403 Forbidden error.

To find the culprit, reactivate your plugins one-by-one until you find which plugin is causing the issue.

After changing the file name of the plugins folder, you should see a number of errors that say plugin file does not exist when you go to the Plugins area on your site:

What happens after renaming the plugins folder

What happens after renaming the plugins folder

To fix this issue and regain the ability to manage your plugins, use your FTP program to change the name of the folder back to plugins. So, if you renamed it to plugins-disabled, just change it back to plugins.

Once you do that, you’ll see the full list of all your plugins again. Only now, they’ll all be deactivated:

Reactivate your plugins one by one

Reactivate your plugins one by one

Use the Activate button to reactivate them one-by-one.

Once you find the plugin that’s causing the issue, you can either reach out to the plugin’s developer for help or choose an alternate plugin that accomplishes the same thing (we’ve collected the best WordPress plugins here).

6. Deactivate CDN Temporarily

If you’re getting 403 forbidden errors on your assets (images, JavaScript, CSS), it could be a problem with your content delivery network (CDN).

In this case, we recommend temporarily disabling your CDN and then checking your site to see if the issue is resolved. If you’re a Kinsta client, click through to your WordPress site within the MyKinsta dashboard, select CDN in the sidebar menu and then click the Disable button.

Screenshot of the MyKinsta dashboard revealing a Disbable button for the CDN.

Disabling the CDN within the MyKinsta dashboard.

7. Check to See If Hotlink Protection Is Misconfigured

Hotlinking is when someone adds an image to their site, but the hosted link is still pointed to someone else’s site. To prevent this, some will set up what is called “hotlink protection” with their host or CDN provider.

When hotlink protection is enabled, it will typically return a 403 forbidden error. This is normal. However, if you’re seeing a 403 forbidden error on something you shouldn’t be, check to make sure hotlink protection is configured properly.

8. Disconnect From Your VPN

Another simple tip, but that can solve this problem.

Some sites block VPN users, which may be why the 403 Forbidden message is showing up for you.

To verify this, disconnect from the VPN and try connecting to the site in another way. Or try switching to a different server provided by your VPN service.

9. Reach Out to Your Hosting Provider

If none of the above solutions worked for you, then we recommend reaching out to your hosting provider. They can most likely help you pinpoint the issue and get you back up and running. If you’re a Kinsta client, open up a support ticket with our team. We are available 24/7.

10. Use the Sitechecker Website Crawler Tool

The Sitechecker Website SEO Checker is able to provide you with a detailed SEO audit report by providing solutions and checkers for your website. There is a website crawler, a site monitoring tool, and a rank tracker amongst other built-in tools.

It’s important to constantly monitor your pages for 403 errors, and you can do this with Sitechecker. You can check your website not only for 403 errors but also for all other errors.

Summary

The 403 Forbidden error means that your server is working, but you no longer have permission to view all or some of your site for some reason.

The two most likely causes of this error are issues with your site’s file permissions or .htaccess file. Beyond that, some plugin issues might also cause the 403 Forbidden error. Or it could be that something is misconfigured with hotlink protection or your CDN.

By following the troubleshooting steps in this guide, you should be able to get your site back to working in no time.


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Get started with a free trial of our Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.

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.

1. You should configure your /etc/hosts file like that:

127.0.0.1   localhost
127.0.0.1   test-site
127.0.1.1   my-hostname
# The following lines are desirable for IPv6 capable hosts. etc...

Where test-site is the second “localhost”. And my-hostname is the “System hostname” defined in /etc/hostname.


2. You should define and enable a Virtual Host (VH):

There is a default HTTP VH. It’s placed in /etc/apache2/sites-available/. The filename is 000-default.conf. You have to edit it (you can rename it, if you want, or make some other .conf files, based on it) and after that you have to enable it.

You can enable it manually through creation of “soft, symbolic link”:

sudo ln -s /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-enabled/

Or you can use Apache2 tool called a2ensite, which make the same:

sudo a2ensite 000-default.conf

Let’s assume there has 3 Virtual Hosts, enabled SSL, and registered private domain (SOS.info for an example):

/etc/apache2/sites-available/http.SOS.info.conf
/etc/apache2/sites-available/https.SOS.info.conf

And one which is created for the purposes of this topic:

/etc/apache2/sites-available/http.test-site.conf

The content of First 2 VHs is:

$ cat /etc/apache2/sites-available/http.SOS.info.conf

<VirtualHost *:80>    
    ServerName SOS.info
    ServerAlias www.SOS.info
    ServerAdmin admin@SOS.info

    # Redirect Requests to SSL
    Redirect permanent "/" "https://SOS.info/"

    ErrorLog ${APACHE_LOG_DIR}/http.SOS.info.error.log
    CustomLog ${APACHE_LOG_DIR}/http.SOS.info.access.log combined       
</VirtualHost>

This one redirects all HTTP requests to HTTPS.

$ cat /etc/apache2/sites-available/https.SOS.info.conf

<IfModule mod_ssl.c>    
    <VirtualHost _default_:443>    
        ServerName SOS.info
        ServerAlias www.SOS.info
        ServerAdmin admin@SOS.info

        DocumentRoot /var/www/html  

        SSLEngine on    
        SSLCertificateFile /etc/ssl/certs/SOS.info.crt
        SSLCertificateKeyFile /etc/ssl/private/SOS.info.key
        SSLCertificateChainFile /etc/ssl/certs/SOS.info.root-bundle.crt
        #etc..
    </VirtualHost>    
</IfModule>

This is the HTTPS VH.

The content of these two files can be posted in one file, but in this case their management (a2ensite/a2dissite)will be more difficult.


The third Virtual Host is that, which is created for our purposes:

$ cat /etc/apache2/sites-available/http.test-site.conf

<VirtualHost *:80>
    ServerName test-site
    ServerAlias test-site.SOS.info

    DocumentRoot /var/www/test-site
    DirectoryIndex index.html

    ErrorLog ${APACHE_LOG_DIR}/test-site.error.log
    CustomLog ${APACHE_LOG_DIR}/test-site.access.log combined

    <Directory /var/www/test-site>
        # Allow .htaccess 
        AllowOverride All
        Allow from All
    </Directory>    
</VirtualHost>

3. With this configuration you should access:

http://localhost     # pointed to the directory of the mine Domain 
https://localhost    # iin our case: /var/www/html (SOS.info), but you should get an error, because the SSL certificate

http://SOS.info      # which redirects to https://SOS.info
https://SOS.info     # you should have valid SSL certificate

http://www.SOS.info  # which is allied to http://SOS.info and redirects to https://SOS.info
https://www.SOS.info # which is allied to https://SOS.info

On the main example you should access and:

http://test-site           # pointed to the directory /var/www/test-site
http://test-site.SOS.info  # which is allied to http://test-site

Try to open the site in the web browser or just try (in the terminal) with next commands:

$ curl -L http://test-site/index.html
$ curl -L http://test-site.SOS.info/index.html

Of course, you need to have some index.html pages in their DocumentRoot 🙂



I will leave next notes by reason of pedantry 🙂


4. You need properly configured `/etc/apache2/apache2.conf`.

Ii is good idea to spend some time to improve your server’s security. These manuals are about the security configuration: 1st and 2nd. Here you can get free SSL certificate. These sites will help you to check your progress: 1st and 2nd.

According to above security manuals /etc/apache2/apache2.conf file must looks like:

Mutex file:${APACHE_LOCK_DIR} default

PidFile ${APACHE_PID_FILE}

Timeout 60

#KeepAlive Off
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

HostnameLookups Off

ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn

IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

Include ports.conf

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

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

AccessFileName .htaccess
<FilesMatch "^.ht">
    Require all denied
</FilesMatch>

LogFormat "%v:%p %h %l %u %t "%r" %>s %O "%{Referer}i" "%{User-Agent}i"" vhost_combined
LogFormat "%h %l %u %t "%r" %>s %O "%{Referer}i" "%{User-Agent}i"" combined
LogFormat "%h %l %u %t "%r" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

IncludeOptional conf-enabled/*.conf
IncludeOptional sites-enabled/*.conf

# Hide Server type in the http error-pages 
ServerSignature Off
ServerTokens Prod

# Etag allows remote attackers to obtain sensitive information 
FileETag None

# Disable Trace HTTP Request
TraceEnable off

# Set cookie with HttpOnly and Secure flag.
# a2enmod headers
Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure

# Clickjacking Attack
Header always append X-Frame-Options SAMEORIGIN

# CX-XSS Protection
Header set X-XSS-Protection "1; mode=block"

# Disable HTTP 1.0 Protocol
RewriteEngine On
RewriteCond %{THE_REQUEST} !HTTP/1.1$
RewriteRule .* - [F]

# Change the server banner @ ModSecurity 
# Send full server signature so ModSecurity can alter it
ServerTokens Full
# Alter the web server signature sent by Apache
<IfModule security2_module>
    SecServerSignature "Apache 1.3.26"
</IfModule>
Header set Server "Apache 1.3.26"
Header unset X-Powered-By

# Hde TCP Timestamp
#   gksu gedit /etc/sysctl.conf
#   >> net.ipv4.tcp_timestamps = 0
# Test: sudo hping3 SOS.info -p 443 -S --tcp-timestamp -c 1

# Disable -SSLv2 -SSLv3 and weak Ciphers
SSLProtocol all -SSLv2 -SSLv3
SSLHonorCipherOrder on
SSLCipherSuite "EECDH+ECDSA+AESGCM EECDH+aRSA+AESGCM EECDH+ECDSA+SHA384 EECDH+ECDSA+SHA256 EECDH+aRSA+SHA384 EECDH+aRSA+SHA256 EECDH+aRSA EECDH EDH+aRSA !aNULL !eNULL !LOW !3DES !MD5 !EXP !PSK !SRP !DSS !RC4"

5. Set up the Firewall.

To allow/deny external access to your web server you can use UFW (Uncomplicated Firewall):

sudo ufw allow http
sudo ufw allow https

To allow only tcp protocol use:

sudo ufw allow http/tcp
sudo ufw allow https/tcp

You can use and the port number directly:

sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

Just in case you can reload the “rules table”:

sudo ufw reload

You can use and UFW’s GUI interface, called gufw.

sudo apt update
sudo apt install gufw
gufw &

Choice the Office profile. It will set: Status:ON, Incoming:Deny and Outgoing:Allow and add your rules.


6. If you have a router don’t forget to forward some ports:

If you have a router and you want your web server to be accessible from Internet, don’t forget to add some port forwarding. Something like this.

Добавить комментарий