Ubuntu-server Apache installation configuration and optimization

Source: Internet
Author: User
Tags install openssl openssl openssl x509 parent directory apache log squid proxy

In Ubuntu and Debian, the APACHE2 main functional modules (Multi-Processing module, multi-channel processor, abbreviated MPM) are divided into different packages, respectively:

Apache2-mpm-event: Event-driven MPM;

Apache2-mpm-perchild: This is just a transitional "fake" package that relies on worker;

Apache2-mpm-prefork: Traditional MPM, compatible with apache1.3, not using threads;

Apache2-mpm-worker: High speed MPM supporting multithreading and multi-process hybrid models;

Ubuntu recommends using Apache2-mpm-worker.

$ sudo apt-get install apache2

Apache configuration file Description:

apache2.conf: Global configuration file, do not easily modify it;

Conf.d/: This directory holds some general configuration;

Envvars: Storage environment variables, generally do not need to be modified;

httpd.conf: User Configuration file;

mods-available/: This directory is installed in the available modules;

mods-enabled/: This directory is already enabled module;

The port of the PORTS.CONF:HTTPD service;

sites-available/The directory is the available virtual host;

sites-enabled/: This directory is a virtual host that has been enabled;

$ sudo a2enmod: View available modules

$ sudo a2dismod: viewing enabled modules

$sudo Apt-cache Search Libapache2-mod: Searching all modules

Ubuntu's APACHE2 is configured to provide virtual hosting support. If your server has only one site, basically do not need to modify the configuration, the virtual host can be used; if there are more than one site, you can copy the default virtual host configuration file to modify, so you can quickly set up multiple Web sites.

Default virtual host path:/etc/apache2/sites-available/default

Create a new virtual host: Suppose we want to create a domain name for www.lgmtest.com the virtual host:

1) Copy default:

$ sudo cp/etc/apache2/sites-available/default/etc/apache2/sites-available/www.lgmtest.com

2) Edit file:

$ sudo vi/etc/apache2/sites-available/www.lgmtest.com

Delete the first line of the Namevirtualhost directive (all virtual hosts retain only one namevirtualhost instruction), and then modify the DocumentRoot path to/var/www/www.lgmtest.com/ (Set yourself), <Directory/var/www/> Modify to <directory/var/www/www.lgmtest.com/>

If you have many virtual hosts, it is recommended that you modify the errorlog and customlog paths.

disables the default virtual host and enables the new www.lgmtest.com virtual Host, and then restart Apache

$ sudo a2dissite default && a2ensite www.lgmtest.com

$ sudo/etc/init.d/apache2 Restart

Details of the virtual host configuration (take the default virtual host as an example)

1.NameVirtualHost: Used to specify the address of the server IP

Grammar Namevirtualhost 192.168.1.1:8080

2.VirtualHost: For the current virtual host.

Syntax <virtualhost IP address [: Port number] [IP address [: Port number]] ... >...<virtualhost/>

3.ServerAdmin: Used to designate the webmaster email address.

4.DocumentRoot: Used to specify the root of the Web site, general set absolute path, otherwise, Apache will consider its parent directory is the path defined by ServerRoot.

The 5.<directory></directory> directives are a pair of instructions that are contained in the middle and are valid only for the specified directory. The directory can be a specified directory, such as:

<Directory/var/www/www.lgmtest.com>

...

</Directory>

In addition, wildcard wildcards expressions expressions are supported to match many directories. Like what:

<Directory/var/www/*.lgmtest.com>......</Directory>

6.Options: Used to configure the attributes of the specified directory, such as whether to allow symbolic links to the directory, whether to use CGI and so on. These features include:

all--> all attributes except MultiViews (default setting);

Execcgi--> allows the directory to run CGI scripts via mod_cgi;

Followsymlinks--> allows symbolic connections to be used in this directory;

Includes--> in this directory allows the use of Mod_include for server-side inclusion;

Includesnoexec--> allows server-side inclusion, but disables "#exec cmd" and "#exec CGI";

indexes--> Allow column directories. If the specified file (such as index.html) is not directoryindex in an accessed directory, the server generates and displays a list of directories;

Multiviews--> allows "content negotiation" to "pay more attention to the graph." "Content negotiation" is generated by mod_negotiation module;

Symlinksifownermatch--> allows only such symbolic links to be used: These symbolic links have the same userid as the owner of the target directory (or file).

In the options directive, you can use the plus minus sign (+|-). In general, if you set up multiple options on a directory, the most special one will be fully received while the others will be ignored; however, if all the options acting on the option directive are preceded by a "+" or "-" sign, this option will be merged-all with "+" option will force the overwrite of the current setting, and all options with the "-" sign will be forced to be removed from the current setting.

7.AllowOverride: For a. htaccess file, you can allow all instructions for the file, or you can allow only certain types of instructions, or all of them.

Syntax: allowoverride all | None | Directive-type [Directive-type] ...

The original Apache default value is allowoverride all, but for security reasons, Ubuntu changed it to AllowOverride None (ignoring the. htaccess file directly).

Tip: AllowOverride is valid only in <Directory> configuration segments that do not contain regular expressions.

8.Order: Used to control the default access state and the order in which allow and deny are in effect. The order can be "Deny,allow" or "Allow,deny". If the former, then the deny is evaluated before the allow instruction, and all accesses are allowed by default. Any accessors that do not match the Deny directive or match the Allow instruction are allowed access, and if the latter, the Allow is evaluated before the deny and all access is denied by default. Any accessors that do not match the Allow directive or match the deny instruction will be prevented from accessing it.

9.Allow: Used to control which hosts are accessible. Control can be based on the definition of host name, IP address, IP range, or other environment variable.

Syntax: Allow from all | Host | env=env-variable [Host | env=env-variable] ...

10.Deny: Used to restrict host access, the syntax and allow are exactly the same.

11.ErrorLog: Defines the location of the error log.

12.LogLevel: The level-level order that controls the verbosity of the log is:

Emerg: Emergency (System not available)

Alert: Immediate measures must be taken

Crit: Fatal condition

Error: Wrong condition

Warn: Warning situation

Notice: General Important situation

Info: General Information

Debug: Debugging Information

13.CustomLog: Defines the path and format of the access log.

Syntax: Customlog file|pipe Format | Nickname [env=[!] Environment-variable]

Customlog Logs/access_log Common

Customlog Logs/access_log "%h%l%u%t \"%r\ "%>s%b"

14.ServerSignature: Used to define the footer of the page generated by the server. This information includes error messages, a list of mod_proxy FTP directories, mod_info output, and so on.

15.Alias: A bit like the Linux LN command, which provides a path alias that makes it easier to use

Syntax: Alias url-path File-path | Directory-path

the implementation of HTTPS

1) Enable Mod_ssl module ;

$ sudo a2enmod SSL

2 Generate certificates and install certificates;

<1> use CA signed certificates (to be charged):

A. First install openssl:$ sudo apt-get install OpenSSL

B. Create key:

$ OpenSSL genrsa–des3–out Server.key 1024 (this is to set the password)

$ OpenSSI genrsa–out Server.key 1024 (this does not set a password)

C. Create a CSR:

$ OpenSSI Req–new–key server.key–out SERVER.CSR

When you are done, send the CSR file to a home Ca,ca to sign it.

<2> use a certificate of your own signature:

$ sudo openssl x509–req–days 365–in server.csr–signkey server.key–out server.crt

$ sudo cp server.crt/etc/ssl/certs

$ sudo cp server.key/etc/ssl/private

3 Modify the virtual host configuration file, restart the Apache service.

Enable SSL. In the VirtualHost section, under the DocumentRoot line, add:

         Sslengine on
         ssloptions +strictrequire
         sslcertificatefile/etc/ssl/certs/server.crt
         Sslcertificatekeyfile/etc/ssl/private/server.key

Note: The top two paths are previously specified.

Restart Apache: $ sudo/etc/init.d/apache2 Restart

Apache Performance Optimization

1. Correct choice of MPM

The event is better suited to situations where users need to have a large number of persistent connections (KeepAlive traffic). The benefit of keepalive is that you can respond to multiple requests in the same TCP connection. This way, you can make an HTML document that contains a large number of pictures accelerate by 50%. KeepAlive is enabled by setting KeepAlive to on in the configuration file.

Prefork implements another MPM that is not threaded and is characterized by stability. It can isolate each request, and if a request fails, it does not affect other requests. The most important thing to use Prefork is to set the maxclients properly. This maxclients value is large enough, but not too large, resulting in Apache memory exceeding the physical memory size.

Worker, the speed is much faster than prefork, can handle relatively massive request. Workers use multiple processes, and each process generates multiple threads, which allows for the stability of a process-based server. The more important two configurations are: Threadperchild (used to control the number of threads allowed per subprocess) and maxclients (control the number of bus processes that are allowed to be established).

2. Optimize Apache configuration

A) To turn off DNS queries: set hostnamelookups to Off;

b Optimize maxclients:

Modify the apache.conf file Ifmodule mpm_worker_module (worker), Ifmodule Mpm_event_module (event), or Ifmodule mpm_prefork_module ( Prefork) Three modules inside the data. MaxClients If you set to more than 256, you need to synchronize the Serverlimit values, because the default value of Serverlimit is 256

c) Optimize keepalive: Set KeepAlive to Off or change the KeepAliveTimeout value to small.

d) Enable compression:

$ sudo a2enmod deflate

$ sudo/etc/init.d/apache2 Force-reload

Configure the type of file to compress (modify/etc/apache2/mods-enabled/deflate.conf)

In general, do not compress pictures, PDFs, MP3 files, etc.

e) using caching (Mod_cache):

One is based on hard disk caching (Mod_disk_cache), one is based on memory cache (Mod_mem_cache);

Enable caching command: $ sudo a2enmod disk_cache.

Add in <VirtualHost> Tags:

          <ifmodule mod_disk_cache.c>
               cacheenable disk/   #表示cache类型为disk, "/" refers to the site root directory, which means caching the entire Web site
                 cacheroot/ Var/www/www.lgmtest.com/cache   #cache目录必须手工创建, where the cache is stored
                 cachedefaultexpire 7200    #失效周期, unit seconds
                 Cachemaxexpire 604800      #最大失效周期, per second
            </IfModule>

If you want a directory not to be cached, add: cachedisable/Not cached directory

Apache Stress Test (AD)

$ sudo ab–n 20000–c http://www.lgmtest.com/

Description: Send 20,000 requests to www.lgmtest.com, 200 at a time.

Apache Security

1) Hide sensitive information:

Add in apache2.conf: Servertokens Prod (default is Full).

2) DDoS attack Prevention:

$sudo Apt-get Install Libapache2-mod-evasive

After installation, Ubuntu automatically starts, and we create a configuration file ourselves:

$sudo Vi/etc/apache2/conf.d/evasive, write the following:

          <ifmodule mod_evasive20.c>
                 doshashtablesize 3097 #哈希表大小, increase can increase the search speed
                    dospagecount 2   # Allows the client to access the same page at a time interval, once less than this interval, the client IP address will be written to the blacklist
                    dossitecount 2    #允许客户机对全站同时进行的并发访问请求数目
                    dospageinterval 1        #定义网页访问计数的时间间隔
                    Dossiteinterval 1         #定义全站访问计数的时间间隔
                    dosblockingperiod  #定义了阻止客户机的时间长短, which does not allow access to blacklisted clients, if accessed, The blocking time is refreshed again, with the default
                 dosemailnotify 277531070@qq.com
                 dossystemcommand "Su–someuser–c '/sbin/...%s
                    ". Doslogdir "var/lock/mod_evasive" 
                    doswhitelist  127.0.0.1   #白名单
                    doswhitelist  127.0.0.*
          </IfModule>

Or add in the httpd.conf file:

          LoadModule evasive20_module  /usr/lib/apache2/modules/mod_evasive20.so
          <ifmodule mod_evasive20.c>
                    doshashtablesize    3097
                    dospagecount        2
                    dossitecount
                    dospageinterval     1
                    Dossiteinterval     1
                    dosblockingperiod
          </IfModule>

Apache Log Analysis

1) Installation Webalizer: $sudo apt-get Install Webalizer

2) Modify the configuration file:

By default, Webalizer installs a daily cron task that automatically analyzes the Apache logs of the previous day on a daily basis. You can set the log file to parse by modifying the configuration file (Modify/etc/webalizer/webalizer.conf):

Logfile/var/log/apache2/access.log.1 the file name to parse

Outputdir/var/www/lgmtesta/webalizer Data Output Directory

LogType CLF: Log type, if you want to analyze the FTP log, to FTP, such as to analyze Squid Proxy server log, to squid.

3) Run Webalizer: $sudo webalizer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.