Install, configure, and optimize apache on ubuntu server

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

 

In ubuntu and debian, the main functional modules of apache2 (MPM) are divided into different software packages:

Apache2-mpm-event: event-driven MPM;

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

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

Apache2-mpm-worker: High-Speed MPM supporting multi-thread and multi-process hybrid model;

 

Apache2-mpm-worker is recommended for Ubuntu.

 

$ Sudo apt-get install apache2

 

Apache configuration file description:

Apache2.conf: global configuration file. Do not modify it easily;

Conf. d/: This directory stores some general configurations;

Envvars: stores environment variables and does not need to be modified;

Httpd. conf: user configuration file;

Mod-available/: available modules installed in this directory;

Mod-enabled/: This directory contains enabled modules;

Ports. conf: the httpd service port;

Sites-available/available virtual hosts under this directory;

Sites-enabled/: This directory contains enabled virtual hosts;

 

$ Sudo a2enmod: view available modules

$ Sudo a2dismod: View enabled modules

 

$ Sudo apt-cache search libapache2-mod: search all modules

 

Apache2 of Ubuntu makes good configuration for providing support for virtual hosts. If your server has only one website, you can use the virtual host without modifying the configuration. If there are multiple websites, you can copy the configuration file of the default virtual host for modification, in this way, you can quickly set up multiple websites.

 

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

 

Create a new VM: Suppose we want to create a VM with the domain name www.lgmtest.com:

1) Copy default:

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

2) edit the file:

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

Delete the NameVirtualHost command in the first line (only one NameVirtualHost command can be reserved for all virtual hosts). Then, change the DocumentRoot path to/var/www/www.lgmtest.com/(set by yourself) and <Directory/var/www/> to <Directory/var/www/www.lgmtest.com/>

If you have many virtual hosts, we recommend that you modify the paths of ErrorLog and CustomLog.

 

Disable the default Vm, enable the new www.lgmtest.com Vm, and restart apache

$ Sudo a2dissite default & a2ensite www.lgmtest.com

$ Sudo/etc/init. d/apache2 restart

 

Detailed description of virtual host configuration (taking the default virtual host as an example)

1. NameVirtualHost: used to specify the ip address of the server

Syntax 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 specify the webmaster email address.

4. DocumentRoot: used to specify the root directory of the website. Generally, the absolute path is set. Otherwise, apache considers its parent directory as the path defined by ServerRoot.

5. The <Directory> </Directory> command is a pair of commands that are contained in the middle and only valid for the specified Directory. This directory can be a specific directory, for example:

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

...

</Directory>

In addition, wildcards and regular expressions are supported to match many directories. For example:

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

6. Options: used to configure the features of a specified directory, such as whether to allow symbolic links in the directory and whether to use CGI. These features include:

All --> All features except MultiViews (default );

ExecCGI --> allows the directory to run CGI scripts through mod_cgi;

FollowSymLinks --> allows symbolic connections in this directory;

Allowed des --> in this directory, mod_include is allowed for server-side inclusion;

IncludesNOEXEC --> Allow Server inclusion, but disable "# exec cmd" and "# exec cgi ";

Indexes --> allow the column directory. If a specified directory does not contain a file named directoryindex.html (for example, index.html), the server generates and displays a directory list;

MultiViews --> allow "multi-view" of "content negotiation ". "Content negotiation" is generated by the mod_negotiation Module;

SymLinksIfOwnerMatch --> only symbolic links are allowed: these symbolic links have the same UserID as the owner of the target directory (or file.

You can use the plus or minus sign (+ |-) in the Options command -). In general, if you set Options multiple times in a directory, the most special one will be fully accepted, while the others will be ignored; however, if "+" or "-" is added before all Options used in the Options command, this option will be merged -- all options with "+" will forcibly overwrite the current settings, and all options with "-" will be forcibly removed from the current settings.

7. AllowOverride: For the. htaccess file. You can allow all commands of the file, or only some types of commands, or prohibit all commands.

Syntax: AllowOverride All | None | directive-type [directive-type]…

The default value of Apache is AllowOverride All. For security reasons, Ubuntu changes it to AllowOverride None (directly ignoring the. htaccess file ).

Tip: AllowOverride is valid only in the <Directory> Configuration segment that does not contain regular expressions.

8. Order: used to control the default access status and the Order in which Allow and Deny take effect. These sequences can be "Deny, Allow" or "Allow, Deny ". If it is the former, Deny is evaluated before the Allow command. By default, all accesses are allowed. Access is allowed to any visitor who does not match the Deny command or matches the Allow command. If it is the latter, Allow is evaluated before the Deny command, and all access is denied by default. Any visitor who does not match the Allow command or the Deny command will be banned from accessing the database.

9. Allow: used to control which hosts can be accessed. It can be controlled based on the host name, ip address, ip range, or other definitions of environment variables.

Syntax: Allow from all | host | env = env-variable [host | env = env-variable]…

10. Deny: used to restrict access to the host. The syntax is identical to that of Allow.

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

12. LogLevel: the order of levels that control the log details is as follows:

Emerg: urgent (unavailable System)

Alert: actions must be taken immediately

Crit: fatal

Error: error

Warn: Warning

Notice: Generally important

Info: Common 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 the error information, the ftp directory list of mod_proxy, and the output of mod_info.

15. Alias: A bit like the Linux ln command, which provides path aliases for your convenience.

Syntax: Alias URL-path file-path | directory-path

 

HTTPS implementation

1) enable the mod_ssl module;

$ Sudo a2enmod ssl

2) Generate and install certificates;

<1> certificate signed by CA (charged ):

A. install openssl first: $ sudo apt-get install openssl

B. Create a key:

$ Openssl genrsa-des3-out server. key 1024 (this is the password)

$ Openssi genrsa-out server. key 1024 (do not set a password)

C. Create a CSR:

$ Openssi req-new-key server. key-out server. csr

After the CSR file is sent to a CA, the CA signs the CSR file.

<2> use a self-signed certificate:

$ 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 VM configuration file and restart the apache service.

Enable SSL. In the VirtualHost segment, add the following content to the DocumentRoot row:

 

SSLEngine on

SSLOptions + StrictRequire

SSLCertificateFile/etc/ssl/certs/server. crt

SSLCertificateKeyFile/etc/ssl/private/server. key

Note: The above two paths are previously specified.

Restart apache: $ sudo/etc/init. d/apache2 restart

 

Apache Performance Optimization

1. Select MPM correctly

Event is suitable for scenarios where users need to have a large number of persistent connections (KeepAlive traffic. The benefit of KeepAlive is that it can respond to multiple requests in the same TCP connection. In this way, an HTML document containing a large number of images can be accelerated 50%. You can enable keepAlive by setting KeepAlive to On in the configuration file.

Prefork implements another non-thread MPM, which is very stable. It can isolate each request. If a request fails, other requests will not be affected. The most important thing to use prefork is to set MaxClients appropriately. The MaxClients value must be large enough, but cannot be too large. As a result, the memory required by apache exceeds the physical memory size.

Worker, which is much faster than prefork and can process relatively massive requests. The Worker uses multiple processes, and each process generates multiple threads, so that the stability based on the process server can be obtained. Two important configurations are ThreadPerChild (used to control the number of threads allowed by each sub-process) and MaxClients (used to control the total number of threads allowed ).

 

2. Optimize apache configuration

A) disable DNS query: Set HostnameLookups to off;

B) Optimize MaxClients:

Modify the data in the IfModule mpm_worker_module (worker), IfModule mpm_event_module (event), and IfModule mpm_prefork_module (prefork) modules in the apache. conf file. If MaxClients is set to exceed 256, the ServerLimit value must be modified synchronously, because the default value of ServerLimit is 256.

C) Optimize KeepAlive: Set KeepAlive to Off or change the value of KeepAliveTimeout to a smaller value.

D) Enable compression:

$ Sudo a2enmod deflate

$ Sudo/etc/init. d/apache2 force-reload

Configure the file type to be compressed (modify/etc/apache2/mod-enabled/deflate. conf)

Generally, images, pdf files, mp3 files, and other files are not compressed.

E) Use the cache (mod_cache ):

One is based on hard disk cache (mod_disk_cache) and the other is based on memory cache (mod_mem_cache );

Enable cache command: $ sudo a2enmod disk_cache.

Add the following to the <VirtualHost> label:

 

<IfModule mod_disk_cache.c>

CacheEnable disk/# indicates that the cache type is disk, and "/" indicates the root directory of the website, indicating that the entire website is cached.

CacheRoot/var/www/www.lgmtest.com/cache # The cache directory must be created manually to store the cache.

CacheDefaultExpire 7200 # expiration cycle, in seconds

CacheMaxExpire 604800 # maximum failure period, in seconds

</IfModule>

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

Apache stress testing (ad)

$ Sudo AB-n 20000-c 200 http://www.lgmtest.com/

Note: 20000 requests are sent to www.lgmtest.com each time.

 

Apache Security

1) hide sensitive information:

Add ServerTokens Prod in apache2.conf (default value: Full ).

2) DDOS attack prevention:

$ Sudo apt-get install libapache2-mod-evasive

After installation, ubuntu will automatically start. We will create a configuration file:

$ Sudo vi/etc/apache2/conf. d/evasive:

 

<IfModule mod_evasive20.c>

DOSHashTableSize 3097 # increase the size of the hash table to increase the search speed

DOSPageCount 2 # Allow the client to access the same page at intervals. Once the interval is smaller than the interval, the Client IP address will be blacklisted.

DOSSiteCount 2 # number of concurrent access requests allowed by the client for the whole site

DOSPageInterval 1 # define the time interval for the web page access count

DOSSiteInterval 1 # define the time interval for full-site access count

DOSBlockingPeriod 10 # defines the length of time for blocking the client. During this period, access from the client that is blacklisted is not allowed. If the access time is blocked, refresh the page again. The default value is 10.

DOSEmailNotify 277531070@qq.com

DOSSystemCommand "su-someuser-C'/sbin /... % S... '"

DOSLogDir "var/lock/mod_evasive"

DOSWhitelist 127.0.0.1 # whitelist

DOSWhitelist 127.0.0 .*

</IfModule>

Or add the following to the httpd. conf file:

 

LoadModule evasive20_module/usr/lib/apache2/modules/mod_evasive+so

<IfModule mod_evasive20.c>

DOSHashTableSize 3097

DOSPageCount 2

DOSSiteCount 50

DOSPageInterval 1

DOSSiteInterval 1

DOSBlockingPeriod 10

</IfModule>

Apache Log Analysis

1) install Webalizer: $ sudo apt-get install webalizer

2) modify the configuration file:

By default, webalizer installs a daily cron task and automatically analyzes the apache logs of the previous day every day. You can modify the configuration file to set the log file to be analyzed (modify/etc/webalizer. conf ):

LogFile/var/log/apache2/access. log.1 file name to be analyzed

OutputDir/var/www/lgmtesta/webalizer data output directory

LogType clf: Log Type. If you want to analyze ftp logs, change it to ftp. To analyze the Squid proxy server logs, change it to squid.

3) Run webalizer: $ sudo webalizer

Author lgm277531070

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.