How to build Apache virtual host and partition logs

Posted by BoxingKing on Tue, 01 Feb 2022 07:25:22 +0100

1, Apache virtual host

(1) Build virtual web host

Virtual web host refers to running multiple web sites in the same server, in which each site does not occupy the whole server independently, so it is called "virtual" web host. Through virtual web host service, we can make full use of the hardware resources of the server, so as to greatly reduce the cost of website construction and operation.

(2) http supported virtual host types

1. Domain name based: use different domain names for each virtual host, but its corresponding IP address is the same. For example, www.benet.com COM and www.accp.com The IP address of the com site is 192.168.80.10 This is the most commonly used type of virtual web host.
2. Based on IP address: different domain names are used for each virtual host, and their corresponding IP addresses are also different. This method requires multiple network interfaces for the server, so it is not widely used. The IP is different and the port is the same.
3. Port based: this method does not use domain name and IP address to distinguish different site contents, but uses different TCP port numbers. Therefore, when browsing different virtual sites, users need to specify the port number at the same time to access.

(3) Access virtual host based on domain name

1. Provide domain name resolution for virtual host
Method 1: deploy DNS domain name resolution server to provide domain name resolution

Method 2: temporarily configure the mapping relationship between domain name and IP address in / etc/hosts file

echo "192.168.80.10 www.benet.com">> /var/www/html/benet/index.html
echo "192.168.200.50 www.accp.com" >> /etc/hosts

If you have used this virtual machine for Apache before, you need to cancel the previous home page file, which can be modified to backup

cd /usr/local/httpd/htdocs
bbs  index.html.bak  index.php.bak

2. Prepare web document for virtual host

mkdir -p /var/www/html/benet
mkdir -p /var/www/html/accp
echo "<h1>www.benet.com</h1>" > /var/www/html/benet/index.html
echo "<h1>www.accp.com</h1>" > /var/www/html/accp/index.html

3. Add virtual host configuration

vim /usr/local/httpd/conf/extra/httpd-vhosts.conf       #Source code compilation and installation of virtual host configuration file path
#vim /etc/httpd/conf.d/vhosts.conf                      #Path to the virtual host configuration file for RPM or YUM installation 

Template file:
<VirtualHost *:80>                                      #Set virtual site area
    ServerAdmin webmaster@dummy-host.example.com        #Set the administrator mailbox. This line can be commented out
    DocumentRoot "/usr/local/httpd/docs/dummy-host.example.com"    #Set site root
    ServerName dummy-host.example.com                   #Set the full domain name of the Web site (host name + domain name)
    ServerAlias www.dummy-host.example.com
    ErrorLog "logs/dummy-host.example.com-error_log"    #Set the path of the error log file
    CustomLog "logs/dummy-host.example.com-access_log" common     #Set the path to access the log file
</VirtualHost>                                          #End tag

Change to:
<VirtualHost 192.168.200.50:80>
    DocumentRoot "/var/www/html/benet"
    ServerName www.benet.com
    ErrorLog "logs/benet.com-error_log"
    CustomLog "logs/benet.com-access_log" common
</VirtualHost>

<VirtualHost 192.168.200.50:80>
    DocumentRoot "/var/www/html/accp"
    ServerName www.accp.com
    ErrorLog "logs/accp.com-error_log"
    CustomLog "logs/accp.com-access_log" common
</VirtualHost>

4. Load a stand-alone configuration file

vim /usr/local/httpd/conf/httpd.conf      #Source code compilation and installation of httpd service main configuration file path
------483 Line uncomment
Include conf/extra/httpd-vhosts.conf      #Load a stand-alone configuration file
---------------------------------------------------------------------------------------
#vim /etc/httpd/conf/httpd.conf           #Path to the httpd service master profile installed by RPM or YUM
IncludeOptional conf.d/*.conf             #The last line is enabled by default

5. Set access control

cd /usr/local/httpd/conf/extra
vim httpd-vhosts.conf          #Add the following at the end
<Directory "/var/www/html">    #Set directory access
    Options None               #Do not enable any server features
    AllowOverride None         #Overriding Apache default configuration is not allowed
    Require all granted        #Allow all hosts access
</Directory> 

systemctl restart httpd.service

Options instruction explanation:
The main function of the Options directive is to control which server features will be enabled for a specific directory. You can configure virtual hosts, directories, and directories in Apache configuration files htaccess file.

Options directive common options:
None: indicates that no server features are enabled
FollowSymLinks: the server allows symbolic connections (soft links) in this directory.
Indexes: if the entered URL corresponds to a file directory on the server, and there is no file specified by the DirectoryIndex directive in the Apache configuration file in this directory (for example: DirectoryIndex.html index. PHP), all files in this directory will be listed.
Multiviews: if the path requested by the client may correspond to multiple types of files, the server will automatically select a file that best matches the client's requirements according to the specific conditions of the client's request. For example, in the file folder of the server site, there is a file named hello Jpg and hello Two files of HTML, which are entered by the user at this time http://localhost/file/helle If there is no subdirectory of Hello. File, the server will try to find it in the subdirectory of Hello. File* And then return the best matching Hello according to the specific situation of the user's request Jpg or hello html
All: indicates all properties except Multiviews. This is also the default setting of the Options command

Allowoverride instruction interpretation:
. htaccess (distributed implicit configuration file): it provides a method to change the configuration for each directory, that is, a file containing specific instructions is placed in a specific directory, in which the instructions act on this directory and all its subdirectories. When alloverride is set to None, the file in the corresponding configuration directory The htaccess file is not read, that is, it cannot take effect. When alloverride is set to A11, it will be read every time a request is made to access the file in the corresponding directory The configuration of htaccess file means that the original Apache instruction will be deleted Instruction rewriting in htaccess file.
In terms of performance and safety, it is generally avoided as much as possible Htaccess file, anything you want to put in The configuration in the htaccess file can be placed in the section of the main configuration file (httpd.conf), which is efficient. Therefore, the Allowoverride property is generally configured as None

Address restriction policy:
Require all granted: allow all hosts to access.
Require all denied: deny access to all hosts,
Require local: only local host access is allowed.
Require [not] host < host name or domain name list >: allow or deny access to the specified host or domain name.
Require [not] IP < IP address or network segment list >: allow or deny network access to the specified IP address.

(4) Access virtual host based on IP address

ifconfig ens33:0 192.168.200.100 netmask 255.255.255.0     #Add virtual network card

After adding the virtual network card, remember to check whether the virtual network card is added successfully

ifconfig ens33:0 192.168.80.100 netmask 255.255.255.0 

vim /usr/local/httpd/conf/extra/httpd-vhosts.conf
<VirtualHost 192.168.80.10:80>					
    DocumentRoot "/var/www/html/benet"			
    ServerName www.benet.com					
    ErrorLog "logs/benet.com-error_log"			
    CustomLog "logs/benet.com-access_log" common
</VirtualHost>

<VirtualHost 192.168.80.100:80>					
    DocumentRoot "/var/www/html/accp"			
    ServerName www.accp.com					
    ErrorLog "logs/accp.com-error_log"			
    CustomLog "logs/accp.com-access_log" common
</VirtualHost>

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

Modify master profile

vim /usr/local/httpd/conf/httpd.conf	
--53 that 's ok--insert
Listen 192.198.80.100:80

Restart the service after setting

systemctl restart httpd 

(5) Access virtual host based on port number

vim /usr/local/httpd/conf/extra/httpd-vhosts.conf
<VirtualHost 192.168.80.10:80>					
    DocumentRoot "/var/www/html/benet"			
    ServerName www.benet.com					
    ErrorLog "logs/benet.com-error_log"			
    CustomLog "logs/benet.com-access_log" common
</VirtualHost>

<VirtualHost 192.168.80.10:8080>					
    DocumentRoot "/var/www/html/accp"			
    ServerName www.accp.com					
    ErrorLog "logs/accp.com-error_log"			
    CustomLog "logs/accp.com-access_log" common
</VirtualHost>

<Directory "/var/www/html"> 
	Options None			
	AllowOverride None		
	Require all granted		
</Directory>
vim /usr/local/httpd/conf/httpd.conf	
--53 that 's ok--insert
Listen 192.198.80.10:8080

Restart service

systemctl restart httpd 

2, Apache connection retention

(1) How to stay connected

vim /usr/local/httpd/conf/extra/httpd-default.conf
KeepAlive On			#Set whether to turn ON the connection holding function, followed by OFF means OFF and ON means ON. You can decide whether to open it according to the concurrent requests of the website, that is, turn ON the connection retention function when the concurrency is high, and turn OFF this function when the concurrency is not high.

MaxKeepAliveRequests 100		#It is used to set the maximum number of requests that can be transmitted in a long connection. If the maximum number of requests exceeds, the connection will be disconnected. The setting of the maximum value depends on the content of the web page in the website. Generally, the number of settings will be more than all elements in the website.

KeepAliveTimeout 5		#Set the maximum interval between multiple requests for a connection from the same client, that is, the connection will be automatically disconnected after this time, so as to avoid the client occupying connection resources.

3, Building Web virtual directory and user authorization restrictions

1. Create user authentication data file

cd /usr/local/httpd/bin
./htpasswd -c /usr/local/httpd/conf/user zhangsan
./htpasswd /usr/local/httpd/conf/user lisi
#-c option means to create a new user data file. By default, it means that the specified user data file already exists. It is used to add a new user or modify the password of an existing user.

cat /usr/local/httpd/conf/user 		#Confirm user data file

2. Add user authorization configuration

vim /usr/local/httpd/conf/httpd.conf
--Last line add--
Alias /test /var/www/html/test		#Set the root directory of the virtual directory, / test is the name of the virtual directory	
		
<Directory "/var/www/html/test">				#Set virtual directory configuration area
	AuthName "Hello!"							#Define the protected domain name, which will be displayed in the authentication dialog box
	AuthType Basic								#Set the type of authentication. Basic indicates basic authentication
	AuthUserFile /usr/local/httpd/conf/user		#Set the path of the authentication file used to save the user account and password
	Require valid-user							#Turn on user authentication. Only legal users in the authentication file can access it
   #authgroupfile /usr/local/httpd/conf/group	#Set the path of the authentication file used to save the group account and password
   #Require user zhangsan						#Allow only specified users to access
   #Require group zhangsan						#Allow access only to specified groups		
</Directory>

3. Verify user access authorization

mkdir -p /var/www/html/test
echo "<h1>this is vdir test</h1>" > /var/www/html/test/index.html
systemctl restart httpd

Browser access in client
http://192.168.80.10:80/test

4, Apache log segmentation

Use Apache's own rotatelogs segmentation tool to automatically segment Apache logs according to the date of each day.

vim /usr/local/httpd/conf/httpd.conf
--275 that 's ok--modify
ErrorLog "| /usr/local/bin/rotatelogs -l /var/log/httpd/error_%Y%m%d.log 86400"		#Split error log
--305 that 's ok--modify
CustomLog "| /usr/local/bin/rotatelogs -l /var/log/httpd/access_%Y%m%d.log 86400" combined	#Split access log

vim /usr/local/httpd/conf/extra/httpd-vhosts.conf
ErrorLog "| /usr/local/bin/rotatelogs -l /var/log/httpd/benet.com-error_%F.log 86400"
CustomLog "| /usr/local/bin/rotatelogs -l /var/log/httpd/benet.com-access_%F.log 86400" combined

#The beginning | is the pipe symbol.
#-The l option indicates that the local time is used as the time base.
#86400 means one day, that is, a new log file is generated every day.

mkdir /var/log/httpd			#Create the directory where the split log files are saved
systemctl restart httpd
ls /var/log/httpd

5, AWStats analysis system

AWStats is an open source log analysis system developed in Perl language. It is used to complete automatic log statistics and analysis.
1. Transfer the software package required to install AWStats to the / opt directory
awstats-7.6.tar.gz

2. Install AWStats software package

cd /opt
tar zxvf awstats-7.6.tar.gz
mv /opt/awstats-7.6 /usr/local/awstats

3. Create a configuration file for the sites to be counted

cd /usr/local/awstats/tools
./awstats_configure.pl
......
Config file path ('none' to skip web server setup):
> /usr/local/httpd/conf/httpd.conf          #Enter the path to the httpd service master profile
Your web site, virtual server or profile name:
> www.kgc.com                   		   	#Enter the domain name of the site to be counted

Everything else is y Or enter

4. Modify the access permission of automatically generated awstats and load the CGI module (APACHE version 2.4 or above needs to load the CGI module)

vim /usr/local/httpd/conf/httpd.conf
ErrorLog "logs/error_log"
CustomLog "logs/access_log" combined
......
--143 that 's ok--
<IfModule !mpm_prefork_module>
	LoadModule cgid_module modules/mod_cgid.so		#note off
</IfModule>
<IfModule mpm_prefork_module>
	LoadModule cgi_module modules/mod_cgi.so		#note off
</IfModule>
......
--Skip to last line modification--
<Directory "/usr/local/awstats/wwwroot">
    Options None
    AllowOverride None
    #Order allow,deny			#Comment out					
    #Allow from all				#Comment out
    Require all granted			#add to
</Directory>

5. Modify the site statistics configuration file

vim /etc/awstats/awstats.www.kgc.com.conf
LogFile="/usr/local/httpd/logs/access_log"		#Modify the access log file location (the log of the virtual host cannot be set due to the log format problem)
DirData="/var/lib/awstats"						#The awstats directory does not exist by default and needs to be created manually


mkdir /var/lib/awstats

6. Perform log analysis and set cron scheduling tasks

systemctl restart httpd
cd /usr/local/awstats/tools/
./awstats_updateall.pl now  	#Update data (obtain log data according to the log file path specified in the site configuration file)
#Note that it's best to update the access before updating the data After the log file is cleared, visit the site again and obtain the log data.

crontab -e
*/5 * * * * /usr/local/awstats/tools/awstats_updateall.pl now

systemctl start crond

7. Visit the AWStats analysis system site

systemctl stop firewalld
systemctl disable firewalld
setenforce 0

echo "192.168.80.10 www.kgc.com" >> /etc/hosts
 Browser access
http://www.kgc.com/awstats/awstats.pl?config=www.kgc.com

8. Optimize web address

vim /usr/local/httpd/htdocs/aws.html
<html>
<head>
<meta http-equiv=refresh content="0;url=http://www.kgc.com/awstats/awstats.pl?config=www.kgc.com">
</head>
<body></body>
</html>

Explanation of HTML file structure:

<html> </html> : be used for HTML Label represented by the outermost layer of the file structure	
<head> </head> : be used for HTML Header tag of web content description information
<body> </body> : Content label used to display web page content
<meta> : Defined HTML Metadata in documents, such as descriptions and keywords for search engines and update frequency. there http-equiv=refresh It is used to realize the automatic jump of web pages

Topics: Linux