📜 ⬆️ ⬇️

The history of creating a home cloud. Part 2. Creating a server - setting LAMP in Debian

On the way to creating our own cloud service, we have just mastered the Debian system . Now it's time for the next step - creating and configuring a web server, on the basis of which you can run Nextcloud.


Table of contents


Part 1. Setting up a Debian environment for everyday use.
Part 2. Creating a server - setting LAMP in Debian
Part 3. Creating a personal cloud - installing and configuring Nextcloud
Part 4. Update 2018 - Debian 9 and Nextcloud 13



Quick chapter navigation


Foreword
Software installation
Setting up an Apache2 web server and accessing it via HTTP and HTTPS protocols
SQL Setup
PHP setup
SSH access setup
Access protection
Web Server Reference
MySQL reference material
Fail2ban reference material



Foreword


In the first part of this story, one of the possible options for configuring the Debian graphical user interface for convenient and familiar (extremely subjective point of view of the author) use by a person who came to Linux from Windows was shown. And if for setting up a virtual machine with Debian, I used only the host system, then I specifically worked only in this virtual machine, searching for information on the Internet, taking notes in Notepadqq or gedit, listening to music through Audacious, opening files through LibreOffice and the like. In this way, you can settle down and feel much more deeply and appreciate the work with the operating system and its environment, which is quite fully functional in the standard Debian package.

At the moment, our system is configured in such a way that in the future you can only use the command line with a console text editor, for example, nano or use the Double Commander file manager with the integrated editor Notepadqq. It is also possible to combine these two methods, for example, by navigating through the system and editing configuration files through the file manager, and all other commands through the console. All methods are equivalent to achieve the final result.

The current goal is to create a server, which this part will be devoted to. The server can be configured with or without the installation and use of the graphical interface. In the second case from the previous part, you can simply skip the sections on installing and configuring the software for the graphical interface and its settings, installing the graphical software packages and vmware-tools.

I see nothing wrong with using a graphical interface when creating a server: if a person is more comfortable, more comfortable and more comfortable to make his first or second server with a graphical environment - why not? In the end, my GUI web server has worked for a year and will work for as many years as necessary. However, you need to keep in mind some points.

Ideally, a once-configured system would have to work without our intervention for a very long time. My server in the “clean” version was set up in two days, and it worked for almost a year without intervention. This means that the graphical interface was used 0.05% of the time the server was active (the computer only worked half a day) and at the same time occupied resources: RAM, disk space, processor time. It is better to direct all these resources to ensure the functioning of the server itself: for example, raise the memory_limit for PHP or fit more user data to the hard disk. In addition, in case of problems and problems when working with a real remote server, it is often much easier to use SSH access . In this context, the presence of a graphical interface is undesirable and that is why the second server in my network already had a virtual machine without a graphical environment, on which only Midnight Commander was installed from the graphical software, which I used to navigate the file system and edit the settings files through its editor mcedit . Therefore, the following is a universal instruction: commands are given with an emphasis on using the command line, however it is assumed that the user sets up a machine with a graphical environment for the very first time, which caused the use of a browser to locally check the availability of the created sites and some features of the mail program.

In the process of creating a server and adding new sites to it, I have accumulated some background information that may be useful to a novice user. I outlined it after the material on installing and configuring the server.

Note
Upon further reading in constructions of the form http: // 127.0.0.1 (https: // 127.0.0.1), the space after http: // (https: //) must be removed when entering into the address bar of the browser. A space is inserted when publishing this article in order to prevent the text engine from automatically converting text into links.



Software installation


Apache and Nginx are a pair of open source web servers, on which about 55% of servers around the world are built. Apache has been the most popular web server since 1995, and I chose it, hoping for good documentation, popularity, and, so to speak, I wanted to start from the beginning. This does not mean that Nginx is worse: Nginx is more efficient in terms of resource consumption and work under load. In the Russian segment of the Internet, the Nginx server takes up about 65%, while Apache - about 18%. Not bad comparative article of two servers is placed on Habré .

Install Apache2 web server:

# apt-get install apache2 apache2-doc

And it's all. Some twenty megabytes and the web server is already installed. No reboot or settings are needed - the server is already able to open HTML pages. However, a modern website on the Internet is not only a collection of static files, styles, fonts, and other things like twenty years ago. A modern website contains scripts written in PHP , and dynamic information (for example, text content, comments, user profiles) is not written to files next to PHP files, but to a special SQL database . For a full server, you must provide support for these technologies. Moreover, it is easy:

# apt-get install mysql-server mysql-client phpmyadmin
# apt-get install php5 php5-mysql libapache2-mod-php5

During the MySQL installation process, you will be asked to set the mysql superuser password and you will need to select the apache2 server to automatically configure how to work with mysql. When installing the phpmyadmin package, I agreed to automatically configure the package and everywhere I entered the mysql superuser password. PHP installation takes place without any requests.

I did not use faster PHP7 or free MariaDB as an alternative open SQL replacement and decided to build my server on the “canonical” LAMP = Linux + Apache + MySQL + PHP using old and proven solutions, in case of problems I could quickly and easy to find information on the Internet.

Three teams (which can actually be reduced to one) and we have locally installed a full-fledged and modern server. It is quite simple!

But setting up a server takes much more time than installing its components. Initially, I wanted to show in this part my typical mistakes, false solutions to the problems and the results to which they led, but it turned out that over the course of a year, I lost a lot of memory, a lot had to be restored from records, so only the work instruction with small comments, allowing to achieve a universal working result.



Setting up an Apache2 web server


First you need to make sure that the web server is running. To do this, open a browser and type the address http: // 127.0.0.1 ( localhost ). A web page should open with an encouraging caption: “Apache2 Debian Default Page. It's works! ” The server really works. If you have a set of 2000 site files, you can place it in the / var / www / html directory and it will most likely open on our server.



All basic web server settings are stored in / etc / apache2. If you open this directory, you can see the main configuration file apache2.conf and the directory conf-available, mod-available, sites-available. These directories contain pre-configured configuration files (so-called snippets), which you can simply use by default, with your own edits, or take them as a template to create your own configurations. For example, in the directory sites-available is the default host configuration file 000-default.conf. If you open and study it, it turns out that this file just sets the path that opens our website at http: // 127.0.0.1: “DocumentRoot / var / www / html”. Moreover, the line “<VirtualHost *: 80>” means that if I release my machine to the local network and access it on port 80 (port for HTTP ), I will open the site located along the path / var / www / html. How to make sure of it?

First you need to know the IP address that was assigned to the virtual machine after it was loaded. To view the configuration of network adapters, run:

# ifconfig

The information displayed on the console makes it easy to determine that the following address is set for the eth0 adapter:

inet addr:192.168.233.138

Now, on the host machine, I open the address http: // 192.168.233.138 in the browser and expect that the familiar page will open. But ... it does not open. After a while, my browser writes: "Connection timed out." And he writes correctly. Indeed, in the first part I turned on the firewall, but I did not open port 80! Fix this:

# ufw allow 80

Again we try to open the address http: // 192.168.233.138 and make sure that the expected page opens. A virtual host in the virtual machine has opened from outside of all this virtualization. We have made a small step in building our own small virtual Internet.

In addition to the -available directories, there are also -enabled directories that contain what is currently "enabled". If you look at them, you can see that these directories contain links to files that are in the directories-available. In the directory sites-enabled at the moment, only one link - to the file /etc/apache2/sites-available/000-default.conf. This is very convenient - we can manage shortcuts to enable or disable hosts without editing their configuration files. In addition, the source of the configuration - one file, regardless of whether this configuration is currently enabled or not, and this prevents errors when something is ruled in one file, and in the other - is forgotten. To disable our host, you need to remove the required shortcut, and to enable it, create it. In order not to delete or create shortcuts manually, it is easier and more reliable to use special utilities.

Disable virtual host:

# a2dissite 000-default

Enable the virtual host:

# a2enssite 000-default

After each change, you need to reload the host configuration or restart the server:

# service apache2 reload

or

# service apache2 restart

So, a basic understanding of how to configure regular hosts in apache is now available, and then I will show an example of how I configured my server to work on the HTTP and HTTPS protocols.

You need to start with the fact that when you turn off the virtual host 000-default, the disconnection as such does not occur. That is, the site as opened from inside and outside of the virtual machine - and it will open regardless of its configuration in the sites-enabled folder. It was unexpected and I spent a relatively long time to understand if I did everything right or understood. Until the end, I didn’t figure it out, apparently because the path / var / www / html is set globally as the default directory for DocumentRoot. Since I didn’t want that something extra was included and available, I decided to get rid of the html directory itself, and for all nested / var / www, by default, deny access.

To configure the virtual host by default, I edited its configuration file:

# nano /etc/apache2/sites-available/000-default.conf

The contents of the configuration file is as follows:

 <VirtualHost *:80> ServerName localhost ServerAdmin user@localhost DocumentRoot /var/www <Directory /var/www> Options FollowSymLinks AllowOverride All Require all denied </Directory> ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> 

With this configuration, I reinstalled the default directory on / var / www, allowed the server to follow symbolic links in this directory, allowed the server to execute all directives declared in the found .htaccess files and denied access to this directory. The logic of these actions is that I can control access to this directory without referring to the settings of the web server at all and without restarting it. Now you need to check this solution.
Transfer the file:

# mv /var/www/html/index.html /var/www/index.html

And delete the directory:

# rm / var / www / html

Restart the server for the new virtual host default settings to take effect:

# service apache2 restart

Create a file:

# nano /var/www/.htaccess

In which we write one line (without quotes): "Require all granted".

To summarize Now there is no path / var / www / html, but the default host is reconfigured to the path / var / www, which has the index.html file, and by default, at the web server level, access to this directory is denied, but is allowed by the content locally there is a .htaccess file.

Open http: // 127.0.0.1 in the browser and see the already familiar page “Apache2 Debian Default Page. It's works. ” Now check the functionality of the “local” access control:
Delete the .htaccess file:

# rm /var/www/.htaccess

And we update the open page in the browser - the page with the notice of access restriction (Forbidden) should open. Yes, it all works, then everything is done correctly.

In principle, these simple settings are enough for the continued smooth operation of the web server. But I thought this was not enough. Now our web server can work only over HTTP. But what about the HTTPS protocol? After all, if in the future to display projects based on this web server on the Internet, the ability to work using this protocol is at least desirable. And I decided to organize HTTPS support based on the creation of a self-signed SSL certificate.

First you need to get an SSL certificate that will be installed on our server. We do not have any domain, and in fact there is no static IP address either. But this is all unimportant, because I will generate the certificate myself, using the means of my system.

Attention! In the instructions below, it is assumed that the server is installed on a “nameless” machine. If you have a real IP or domain name, then you need to specify them in three places: <Common Name IP / Domain>; <ServerName IP / Domain>; <Redirect "/" "https: // IP / Domain /"> - in the corresponding constructions, replace IP / Domain with IP address or domain name. In the text below, instead of IP / Domain, localhost is used.

Generate SSL certificate:

# openssl req -x509 -nodes -days 3650 -newkey rsa: 2048 -keyout /etc/ssl/private/apache-selfsigned.key -out /etc/ssl/certs/apache-selfsigned.crt

This command will create a self-signed X.509 standard certificate for as long as 10 years with the password protection option skipped with a passphrase - it is necessary that the Apache server has the ability to read the file without user intervention, because after setting the password, you will have to enter it after each boot or reboot. server. Together with the certificate, a new RSA key for 2048 bits will be created, with which the certificate will be signed. The –keyout and –out options indicate the ways in which OpenSSL should generate a key and certificate.

In the process of creating a certificate, questions will be asked, to which I have indicated the following data:

Country Name = MW
State or Province Name = Sun System
Locality Name = Lunar
Organization Name = Hellium Inc.
Organizational Unit Name = 2
Common Name = localhost
Email Address = user @ localhost

Next, you need to create Diffie-Hellman keys to ensure PFS support:

# openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048

Dots and plus signs will run in the terminal and after the end of the cartoon you can create an ssl-params.conf file, which will define the SSL parameters for the server:

# nano /etc/apache2/conf-available/ssl-params.conf

For a secure, up-to-date setup, I used the code generated in the generator to configure SSL on mozilla.imtqy.com . In the generator, I chose the Apache2 server, the Modern profile, and correctly set the server versions and OpenSSL, which can be found in the following commands:

# apache2 -v
# openssl version

As a result, I got the following text:

 # 14-01-2018 / for apache2 2.4.10 & openssl 1.0.1t # from https://mozilla.imtqy.com/server-side-tls/ssl-config-generator/ # parametrs help: https://raymii.org/s/tutorials/Strong_SSL_Security_On_Apache2.html # modern configuration, tweak to your needs SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1 SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256 SSLHonorCipherOrder on SSLCompression off # OCSP Stapling, only in httpd 2.3.3 and later SSLUseStapling on SSLStaplingResponderTimeout 5 SSLStaplingReturnResponderErrors off SSLStaplingCache shmcb:/var/run/ocsp(128000) 

Now configure the virtual host with SSL support:

# nano /etc/apache2/sites-available/default-ssl.conf

The text of this file I led to the following form:

 <IfModule mod_ssl.c> <VirtualHost _default_:443> ServerAdmin user@localhost ServerName localhost DocumentRoot /var/www <Directory /var/www> Options FollowSymLinks AllowOverride All Require all denied </Directory> # HSTS (mod_headers is required) (15768000 seconds = 6 months) Header always set Strict-Transport-Security "max-age=15768000" ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLEngine on SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key <FilesMatch "\.(cgi|shtml|phtml|php)$"> SSLOptions +StdEnvVars </FilesMatch> <Directory /usr/lib/cgi-bin> SSLOptions +StdEnvVars </Directory> BrowserMatch "MSIE [2-6]" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown </VirtualHost> </IfModule> 

From the above, it follows that in our capacity as the DocumentRoot directory we also defined / var / www, access to which is configured in the same way as the previous settings. The HSTS mechanism is enabled , which contributes to the forced connection establishment through the HTTPS protocol. SSL support is included, indicating the certificate and key used, and support for processing certificate data in PHP and CGI scripts is included. The last section is designed to ensure compatibility with earlier versions of Internet Explorer and, in general, is not necessary.

Now we make the final touches.

Open the port for SSL:

# ufw allow 443

Enable apache modules for SSL and HSTS support:

# a2enmod ssl
# a2enmod headers

Enable SSL configuration:

# a2enconf ssl-params

Enable the virtual host with SSL support:

# a2ensite default-ssl

Restart the server to accept all new settings:

# service apache2 restart

Here comes an interesting point - testing the functionality of a new tuned system.

Create a file:

# nano /var/www/.htaccess

In which we write one line: "Require all granted".

Open in the browser https: // 127.0.0.1. The page about the unknown certificate should open, after its acceptance (one-time or permanent permission), the already familiar page with the notification about the launched web server will open.

Delete the .htaccess file:

# rm /var/www/.htaccess

And we update the open page in the browser - the page with the notice of access restriction (Forbidden) should open. Everything works correctly. Now our sites are accessible via both HTTP and HTTPS.

HTTP access can be left enabled, disabled or forced redirected to HTTPS.

For HTTP enabled access, you do not need to do anything, since the server processes the requests for ports 80 and 443 individually and our site in the / var / www folder will open both via HTTP and HTTPS.

To disable access via HTTP, simply disable the corresponding virtual host and restart the web server:

# a2dissite 000-default
# service apache2 restart

Now, if you open http: // 127.0.0.1 in the browser, the page with the Not Found Page notification should open.

The most interesting third option. In this case, HTTP formally remains enabled, but data processing will be forcibly redirected via HTTPS.

To do this, first enable the redirection module:

# a2enmod rewrite

Now open the file 000-default.conf:

# nano /etc/apache2/sites-available/000-default.conf

And before the closing tag add the text below:

 RewriteEngine On RewriteCond %{HTTPS} off RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [NC,R=301,L] 

Restart the server:

# service apache2 restart

Create a file:

# nano /var/www/.htaccess

In which we write one line: "Require all granted".

Now, if you open the address http: // 127.0.0.1 in the browser, we will automatically redirect to https: // 127.0.0.1 with a warning about an unknown certificate (if it was not previously listed as an exception in the browser), after accepting which the familiar page with the notification of the running web server.



SQL Setup


To configure mysql for the first time, just run the following command:

# mysql_secure_installation

After entering the mysql root password, I answered the questions asked in the following order:


To test the performance of mysql, you can run the following command:

# mysql -uroot -p

After entering the mysql superuser password, we see the mysql prompt - it means the service is up and running. You can exit the mysql terminal by typing the "exit" command.

To check phpmyadmin operability, open the address http: // 127.0.0.1/phpmyadmin in the browser. If a page opens with an invitation to enter phpmyadmin, the service is up and running.



PHP setup


After installing PHP, I opened its settings file:

# nano /etc/php5/apache2/php.ini

And he brought some parameters to the following form:


With the help of the PHP module, you can provide caching of data in memory. Caching is useful when server load is high for data that generates a large amount of resources, for example, the results of database queries or processing “heavy” pieces of a site template. As a caching server, I chose the memcached module.

Installing memcache:

[ This text was written specifically for the site geektimes.ru by AlexanderS .
Reference to the source is optional, but its mention is highly desirable! ]

# apt-get install memcached php5-memcached

Let's look at the service configuration settings:

# nano /etc/memcached.conf

In the settings, I increased the size of the memory used for caching: -m 64 -> -m 256. And I checked the presence of the operation mode only in the local zone: -l 127.0.0.1.

Restart the caching service and web server:

# service memcached restart
# service apache2 restart

Now you need to make sure that the service is working. To do this, create a file:

# nano /var/www/info.php

And add the following text to it:

 <?php phpinfo (); ?> 

We do not forget to check for the presence of the .htaccess file in the / var / www directory with the corresponding permission content, if it is not there, we create it.

Now you can open in the browser http: // 127.0.0.1/info.php - a page should open with information about PHP, in which you need to check the presence of the memcached section in it. If the table appeared - PHP works.

You can check the running memcached service as follows:

$ ps -aux | grep memcached

The terminal should return a string containing memcached settings.

Creating a mail stub for PHP

At PHP settings, the shell script was specified as the sendmail_path parameter. The function of this script is to save the letters sent via the standard php mail () function on the local machine, in some convenient folder, and not send them somewhere.

Create a file:

# nano /usr/bin/fake_semdmail.sh

With the following content:

 #!/bin/sh prefix="/var/mail/sendmail/new" numPath="/var/mail/sendmail" if [ ! -f $numPath/num ]; then echo "0" > $numPath/num fi num=`cat $numPath/num` num=$(($num + 1)) echo $num > $numPath/num name="$prefix/letter_$num.txt" while read line do echo $line >> $name done chmod 777 $name /bin/true 

Make this file executable:

# chmod + x /usr/bin/fake_semdmail.sh

Create the necessary directories that may be needed in case of setting up the collection of letters by the mail program:

# mkdir / var / mail / sendmail / var / mail / sendmail / cur / var / mail / sendmail / new / var / mail / sendmail / tmp

And we assign rights so that the server can write files in this folder:

# chmod 777 -R / var / mail / sendmail

Now all outgoing emails will be added to / var / mail / sendmail. You can view them with a text editor, or you can collect them with a mail program. Included with the pre-installed Debian software is the Evolution mail client. When setting up an account, select “Maildir in Maildir format” as the server type and specify the path to the mail directory (/ var / mail / sendmail), and “Sendmail” as the server.

Everything. In general, we have finished with the server - a universal virtual machine has been received, on the basis of which you can build your network services. I left both HTTP and HTTPS accessed. However, after gaining experience in creating and configuring a server, as well as adding sites (see below) to it, I would recommend creating a new virtual machine with a server without a graphical interface as more optimal in terms of resource consumption.



SSH access setup


A server would not be a full-fledged server without access via SSH. The so-called "shell" allows you to quickly and safely connect to a remote server, using, for example, a small program putty, - on the local computer, we get direct access to the terminal of the remote server.

Service installation:

# apt-get install ssh

Let's open the port for SSH (actually, the default port should be number 22, but below I have redefined the port in the SSH configuration):

# ufw allow 106

To organize access for our user user, you need to open the file:

# nano / etc / ssh / sshd_config

And add the directive to the end of the file:

AllowUsers user

In addition, for security reasons, I made the following changes to this file:


After that we restart the service:

# service sshd restart

Now I can run the putty program on the host machine and connect to my server in console mode by entering the connection address 192.168.233.138, port 106 and the user name user.When connecting, you must answer affirmatively on the acceptance of keys and enter the password of the user user. If you need to execute commands from the superuser, you can use the already known command su.



Access protection


I did not begin to protect the web server from DDoS, initially believing that if it will be hosted on a VPS / VDS, then hosting will provide effective protection, and if you make your server “sticking out” on the Internet, then this issue should be dealt with seriously and this is the topic separate article. Protection from Slow HTTP DDoS is done relatively simply in accordance with numerous instructions on the Internet, but it will not save from a distributed attack made from many different IP addresses.

With DDoS, our server will simply stop working for a while. But after the attack, which will not last forever, the server will be restored. But if someone manages to get access via SSH, then control over the server will be lost, and the data on it will be compromised, so controlling access to the server via SSH is a sensible idea.

The simplest and most trivial thing you can do is change the standard port, which we did when configuring SSH. Five years ago, I “put up” a newly created server on the Internet at a recently received real IP address and was surprised that during the week the server existed, about which no one knew anything yet, a large number of records of unsuccessful authorization attempts accumulated in the system logs Ssh and ftp. It is obvious that in the modern Internet there is a considerable number of service-robots that are looking for computers with open ports and trying to connect to them, going through passwords on an existing database or using the brute force method.

Fortunately for us, there is such a thing as fail2ban:

# apt-get install fail2ban

Immediately after installation, the utility is already configured to protect most ports, and if more than six failed attempts to connect appear in the system logs for ten minutes, the intruder will be blocked for ten minutes. The mechanism of the work of fail2ban is quite simple - on certain triggers, so-called jails are triggered, which determine the action intended to protect the application.

The blocking parameters can be set individually:

# nano /etc/fail2ban/jail.local

In the created file, you must specify the settings that will be replaced by the existing ones by default. An example of my file content:

# общие настройки
[DEFAULT]
ignoreip = 127.0.0.1
bantime = 2592000
findtime = 43200
maxretry = 6
banaction = iptables-multiport
# настройка отправки сообщения на почту
destemail = user@localhost
sendername = Fail2Ban
mta = sendmail
action = %(action_mwl)s

# защита SSH
[ssh]
enabled = true
port = 106
filter = sshd
logpath = /var/log/auth.log

# выявляем неудачные попытки ввода пароля
[apache]
enabled = true
port = http,https
filter = apache-auth
logpath = /var/log/apache*/*error.log

# выявляем потенциальные сканирования для применения эксплойтов и php уязвимостей
[apache-noscript]
enabled = true
port = http,https
filter = apache-noscript
logpath = /var/log/apache*/*error.log

# выявляем попытки переполнения Апача
[apache-overflows]
enabled = true
port = http,https
filter = apache-overflows
logpath = /var/log/apache*/*error.log
maxretry = 2

# выявляем неудачные попытки в поиске домашней директории на сервере
[apache-nohome]
enabled = true
port = http,https
filter = apache-nohome
logpath = /var/log/apache*/*error.log
maxretry = 2


The above setting allows you to not control local access, and with six incorrect login attempts, within 12 hours, the attacker's IP address is banned using iptables for 30 days. It controls not only port access for SSH, but also suspicious actions aimed at destabilizing the operation of the web server.



Web Server Reference


Start, stop and restart the server:

# service apache2 start
# service apache2 stop
# service apache2 restart


Restarting server configurations:

# service apache2 reload

Enabling and disabling host test:

# a2ensite test
# a2dissite test


Enabling and disabling test configuration:

# a2enconf test
# a2disconf test


Check file syntax (should return: “Syntax OK”):

# apache2ctl configtest

Option to add a site with HTTP or HTTPS access using an existing virtual host

Suppose you need to add a new site to our server, located in the site.com directory, located in / home / user / www. This can be convenient, since the user will not need to leave the limits of his home directory when working with the site.

We set permissions for the user directory (just in case):

# chmod 755 / home / user

Create a directory for the site:

$ mkdir / home / user / www /home/user/www/site.com Place a

symbolic link to the site directory:

# ln -s /home/user/www/site.com /var/www/site.com

To add access via HTTP, open the file:

# nano /etc/apache2/sites-available/000-default.conf

Or to add access via HTTPS open the file:

# nano /etc/apache2/sites-available/default-ssl.conf

And add to the open file the following content before the closing tag / VirtualHost:

 <Directory /var/www/site.com> Options FollowSymLinks AllowOverride All Require all granted </Directory> 

Restarting the web server:

# service apache2 restart We

check the availability of the site at http: // 127.0.0.1/site.com or https: // 127.0.0.1/site.com (the verification procedure - see below). It should be noted that the site will open regardless of the presence of the .htaccess file, since the directive: Require all for is set for the site directory.

The option to add a site with access via HTTP or HTTPS using a new virtual host and setting up access to the site via its domain name, not IP.

Task conditions are the same as above: let's say we need to add a new site to our server located in the site directory .com located in / home / user / www. But now I also want to access the site by typing in the browser line only its domain name.

We set permissions for the user directory (just in case):

# chmod 755 / home / user

Create a directory for the site:

$ mkdir /home/user/www/site.com Place a

symbolic link to the site directory:

# ln -s / home / user /www/site.com /var/www/site.com

To add HTTP access, create a file:

# nano /etc/apache2/sites-available/site.com.conf

And add the following content to it:

 <VirtualHost *:80> ServerName site.com ServerAlias www.site.com ServerAdmin user@localhost DocumentRoot /var/www/site.com <Directory /var/www/site.com> Options FollowSymLinks AllowOverride All Require all granted </Directory> # Redirect HTTP->HTTPS #RewriteEngine On #RewriteCond %{HTTPS} off #RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [NC,R=301,L] ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost> 

Or, to add access via HTTPS, create the file:

# nano /etc/apache2/sites-available/site.com-ssl.conf

And add the following content to it:

 <IfModule mod_ssl.c> <VirtualHost _default_:443> ServerName site.com ServerAlias www.site.com ServerAdmin user@localhost DocumentRoot /var/www/site.com <Directory /var/www/site.com> Options FollowSymLinks AllowOverride All Require all granted </Directory> # HSTS (mod_headers is required) (15768000 seconds = 6 months) Header always set Strict-Transport-Security "max-age=15768000" ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLEngine on SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key <FilesMatch "\.(cgi|shtml|phtml|php)$"> SSLOptions +StdEnvVars </FilesMatch> <Directory /usr/lib/cgi-bin> SSLOptions +StdEnvVars </Directory> BrowserMatch "MSIE [2-6]" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown </VirtualHost> </IfModule> 

Add the line “127.0.0.1 site.com” to

/ etc / hosts : # echo >> / etc / hosts 127.0.0.1 site.com

Activate the HTTP host:

# a2ensite site.com.conf

Or activate the HTTPS host:

# a2ensite site. com-ssl.conf

Restarting the web server:

# service apache2 restart We

check the availability of the site at http: // site.com or https: // site.com (test method - see below). It should be noted that the site will open regardless of the presence of the .htaccess file, since the directive: Require all for is set for the site directory.

All actions are performed inside the guest virtual machine. It would be interesting to "open" the site in the browser of the host system. It is not difficult. We know the domain name and the IP address of the guest machine. If the Windows host system, you need to open the file c: \ Windows \ System32 \ drivers \ etc \ hosts and at the very end add the following line:

192.168.233.138 site.com

After this change, the computer or host system will have to restart. Now, when opening site.com in a browser, the call to it will be redirected to our virtual machine. In fact, we did the simplest routing on our personal Internet at the level of the host operating system.

If you need access to a virtual host only via HTTPS, but do not want to lose connections using the HTTP protocol, you can set up a redirect:

- create the file /etc/apache2/sites-available/site.com.conf using the above instructions, if it is not created
- in the /etc/apache2/sites-available/site.com.conf file, uncomment the three lines of RewriteEngine / RewriteCond / RewriteRule
— activate the host site.com.conf if it is not activated
- restart the server: # service apache2 restart

Checking the efficiency of the added site

The easiest way to check the availability of a site is to place the index.html file with some content in its root directory.

Create the index.html file:

$ nano /home/user/www/site.com/index.html

And add the following content to it:

 <html> <head> <title>TEST OK</title> </head> <body> <h1>TEST OK</h1> </body> </html> 

Depending on the method of adding the site, open the browser address http: // 127.0.0.1/site.com (https: 127.0.0.1/site.com) or http: // site.com (https: // site.com ) - the page containing the text "TEST OK" should open.



MySQL reference material


Creating user user123 with password pass123 and db123 database via console.

Log in to mysql by entering the mysql superuser password when prompted:

# mysql -u root -p

And create a database (you do not need to type the “mysql>” prefix, a semicolon is required at the end):

mysql> CREATE DATABASE `db123`;

Create user user123 with password pass123:

mysql> CREATE USER 'user123' @ 'localhost' IDENTIFIED BY 'pass123';

Grant user privileges to the database:

mysql> GRANT ALL PRIVILEGES ON `db123`. * TO 'user123' @ 'localhost';

Update privilege table:

mysql> FLUSH PRIVILEGES;

Quit mysql:

mysql> exit

For verification, open the address http: // 127.0.0.1/phpmyadmin and log in with the user123 / pass123 access details. Must open access to the database db123.

Change root password mysql from pass123 to pass456:

# mysqladmin -uroot -ppass123 password pass456

Change user password from user123 from pass123 to pass456:

# mysqladmin -uuser123 -ppass123 password pass456

Delete user123 user:

mysql> DROP USER 'user123' @ 'localhost' ;

Deleting a db123 table:

mysql> DROP DATABASE `db123`;



Fail2ban reference material


Restarting the service:

# service fail2ban restart

Checking the running rules:

# fail2ban-client status

Detailed statistics on the sshd rule:

# fail2ban-client status ssh

Unbanking:

# fail2ban-client set ssh unbanip Banned_IP



Return to the beginning, to the table of contents .



The history of creating a home cloud.Part 2. Creating a server - setting LAMP in Debian.
Text version: 1.0.0.
Date of first publication: 01/30/2018.
Last edited date: hh.hh.hhhh.

Update log
1.0.0 [30-01-2018]
The first version.
Describes the installation and configuration of LAMP in Debian 8.7.x.

Source: https://habr.com/ru/post/409915/