Apache Common function Combat

Source: Internet
Author: User
Tags curl php file rar zip apache log

Apache is the first Web server to use, and a in LAMP refers to it. It is widely used because of its open source, stability, security and other characteristics. A previous article has documented how to build a lamp architecture, building is only the first step, the most important of which is the Apache service, is also the core of lamp. The features that are often used since Apache are documented below. One, Apache three modes of Operation

Apache has a total of 3 stable MPM modes (multi-process processing modules), which are prefork, worker, event. http-2.2 version of httpd the default MPM mode for prefork,2.4 version of HTTPD is the event operation mode. Can be viewed through httpd-v.

[Root@linuxblogs ~]# Httpd-v | Grep-i "Server MPM" 
server Mpm:prefork

When compiling, you can specify by configure parameters:

--with-mpm=prefork|worker|event

1. Prefork Working mode

When Apache starts, it will fork some sub-processes in advance and wait for the request to come in. This is done to reduce the overhead of frequently creating and destroying processes. Each child process has only one thread, and within a single point in time, only one request can be processed.

Advantages: Mature and stable, compatible with all new and old modules. At the same time, there is no need to worry about thread safety.

disadvantage: a process consumes more of the system resources, consuming more memory. Moreover, it is not good at handling high concurrent requests.

2. Worker working mode

Multi-process and multi-threaded blending modes are used. It also pre-fork several sub-processes (a smaller number), and then each child process creates some threads, including a listener thread. Each request comes over and is assigned to 1 threads to service. Threads are lighter than processes because threads typically share the memory space of the parent process, so memory consumption is reduced. In high concurrency scenarios, the performance is better because there are more threads available than prefork.

Pros: take up less memory and perform better with high concurrency.
Disadvantage: You must consider thread-safe issues.

3. Event Working mode

It is much like the worker pattern, and the biggest difference is that it solves the problem of resource wasting for long-occupied threads under the keep-alive scenario. In the event mpm, there will be a dedicated thread to manage these keep-alive types of threads, and when there is a real request coming in, pass the request to the service thread, and then allow it to be released when the execution is complete. This enhances the request processing capability in high concurrency scenarios.

HTTP uses keepalive to reduce the number of TCP connections, but because a server thread or process needs to be bound, a busy server consumes all the threads. The Event MPM is a new model for solving this problem, which separates the service process from the connection. When the server is processing fast and has a very high CTR, the number of threads available is a critical resource constraint, and the event MPM method is the most efficient, but cannot work under HTTPS access.

Second, The Apache user authentication

Sometimes, we need to give some special access to set up a user authentication mechanism to increase security. For example, our personal site, generally have a management background, although the management of the background itself has a password, but we are more secure, you can set up a layer of user authentication.

1. Edit the configuration file

Vim/usr/local/apache2/conf/extra/httpd-vhosts.conf

In the corresponding virtual host configuration, add the following configuration: (bold part is added content)

<virtualhost *:80> 
 documentroot "/usr/local/apache2/htdocs" 
ServerName www.123.com 
Serveralias       www.abc.com 
 <Directory/usr/local/apache2/htdocs/admin.php> 
 allowoverride authconfig 
 AuthName "Please input acount."        
 authtype Basic 
 AUTHUSERFILE/USR/LOCAL/APACHE2/HTDOCS/.HTPASSWD 
 require valid-user 
 </Directory> 
< /virtualhost>

Description: First specify which directory to validate, AuthName custom, authuserfile specify where the user password file is.

2. Create a user name and password file for encryption

Htpasswd-c/usr/local/apache2/htdocs/.htpasswd Liwei 
htpasswd-m/usr/local/apache2/htdocs/.htpasswd Admin

When the first user is created, the-C option creates a. htpasswd file, and the-m option adds the user, following the prompts for the password.

3. Restart Apache Service

Apachectl-t 
Apachectl Graceful

Check that the configuration is correct, then use graceful equivalent to the reload configuration, without restarting the Apache service, the same effect. Test, enter the password via browser input www.123.com/admin.php prompt.

Third, set the default Virtual host

The default virtual host is the first virtual host in a configuration file. About the default virtual host has a feature, usually resolves to this server domain name, no matter what domain name, as long as in the configuration file is not configured, then will be access to this host. If we use IP access directly, we will visit this site. In order to avoid the confusion of others, so should be the default is the first virtual host to be banned. We have banned the use of allow,deny statements.

1. Configure the default virtual host

Vim/usr/local/apache2/conf/extra/httpd-vhosts.conf

Add a record for a virtual host:

<virtualhost *:80> 
 documentroot "/var/123" 
 ServerName xxxxx.com.cn 
 <directory/var/123 > 
 Order allow,deny 
 deny from all 
 </Directory> 
</VirtualHost>

Create the/var/123 directory, and set 600 permissions that daemon users cannot access:

mkdir/var/123 
chmod-r 600/var/123

2. Restart Apache Server

Apachectl-t 
Apachectl Graceful

If using IP or other resolved domain name access, the discovery hint:

Forbidden you do have permission to access/on the this
server.

Four, the domain name 301 jumps

A site will inevitably have multiple domain names, and multiple domain names must have a primary and secondary, such as my site can be accessed with two domain names: www.itepub.cn and www.linuxblogs.cn But everyone found that no matter which domain name I access, Will eventually jump to Www.linuxblogs.con. This behavior is called the domain name jump, here the 301 is a status code, jump except 301 and 302,301 is a permanent jump, 302

is a temporary jump, the site must be set to 301, so the search engine is relatively friendly.

1. Configure the domain name jump

# vim/usr/local/apache2/conf/extra/httpd-vhosts.conf 
<ifmodule mod_rewrite.c> 
 RewriteEngine on 
   
     Rewritecond%{http_host} ^www.abc.com$ 
 rewriterule ^/(. *) $ http:<span>//www.123.com/$1 [R=301,L] 
</IfModule>
   

Configured as: When accessing AAA, jump to the 123 site.

2. Configure multiple domain name jumps

<ifmodule mod_rewrite.c> 
 rewriteengine on 
 rewritecond%{http_host} ^www.abc.com$ [OR] 
 Rew Ritecond%{http_host} ^www.abcd.com$ 
 rewriterule ^/(. *) $ http:<span>//www.123.com/$1 [R=301,L] 
< /ifmodule>

3. Restart the server and test

Apachectl-t 
Apachectl Graceful

Test:

# curl-x192.168.0.8:80 Www.abc.com-I 
http/1.1 301 Moved Permanently 
date:tue, Oct 15:48:10 GMT 
   server:apache/2.2.31 (Unix) php/5.5.38 
location:http://www.123.com/ 
# curl-x192.168.0.8:80 Www.abcd.com-I 
http/1.1 301 Moved Permanently 
date:tue, Oct 15:48:49 GMT c7/>server:apache/2.2.31 (Unix) php/5.5.38 
location:http://www.123.com/ 
content-type:text/html; charset= Iso-8859-1

Through the above tests, it is found that either ABC or ABCD can jump to the www.123.com domain name and access it through the browser.

V. Apache log cutting

Every time we visit a website, several logs are logged. Of course, the premise is that the log has been set, the log does not manage, the length of time the log file will be more and more large, how to avoid producing such a large log file. In fact, Apache has a configuration that allows the logs to be archived according to our needs, such as a new log every day, or a new log per hour.

1, first simple set the path name of the log

Vim/usr/local/apache2/conf/extra/httpd-vhosts.conf

The edit adds the following:

Errorlog "Logs/error.log" 
customlog "Logs/access.log" combined

Specifies that the log is stored in the/usr/local/apache2/logs directory in the format Error.log and access.log,combined for the log display, the log format can refer to the format specified in the configuration file httpd.conf, as follows:

Logformat "%h%l%u%t \"%r\ "%>s%b \"%{referer}i\ "\"%{user-agent}i\ "" Combined 
Logformat "%h%l%u%t \"%r\ "% >s%b "Common

2. Set Apache log Segmentation

Also edit the configuration file httpd-vhosts.conf

Errorlog "|/usr/local/apache2/bin/rotatelogs-l/usr/local/apache2/logs/aaa-error_%y%m%d.log 86400" 
CustomLog " |/usr/local/apache2/bin/rotatelogs-l/usr/local/apache2/logs/aaa-access_%y%m%d.log 86400 "combined

Errorlog is the error log, and Customlog is the access log. | is the pipe character, meaning to give the generated log to rotatelog this tool, and this tool is Apache's own cutting log tool. The function of-L is to calibrate the timezone to UTC, which is Beijing time. 86400, the unit is the second, exactly one day, then the log will be cut once a day. The last combined is the log format, which is defined in the httpd.conf.

Vi. logging of specified file types is not logged

If a website access is particularly large, then the access log will be many, but there are some access logs we can actually ignore, such as some of the site's pictures, as well as JS, CSS and other static objects. The access to these files is often huge, and even if the logs are not used, how do you ignore the logs without logging them?

1, the configuration log does not record the access to the picture

Vim/usr/local/apache2/conf/extra/httpd-vhosts.conf

The relevant configurations are:

Setenvif Request_uri ". *\.gif$" image-request 
setenvif request_uri ". *\.jpg$" Image-request SetEnvIf Request_ 
URI ". *\.png$" image-request 
setenvif request_uri ". *\.bmp$" image-request setenvif 
request_uri ". *\.swf$" ima Ge-request 
setenvif Request_uri ". *\.js$" image-request 
setenvif request_uri ". *\.css$" Image-request 
C Ustomlog "|/usr/local ... _%y%m%d.log 86400" 
combined env=!image-request

Note: On the basis of the original log configuration, added some image-request definition, such as GIF, JPG, BMP, SWF, JS, CSS, such as the end of the full mark as Image-request, and then add a tag after the configuration log env=! Image-request, which means to take the reverse.

Vii. Configuring a static cache for Apache

Said static file refers to the picture, JS, CSS and other files, the user visits a site, in fact, most of the elements are pictures, JS, CSS, etc., these static files will be cached by the client's browser to the local computer, the purpose is to request the next time no longer go to the server download, so that speed and improves the user experience. However, these static files can not always be cached, it always has some timeliness, then you have to set this expiration time.

1. Configure Static caching

# vim/usr/local/apache2/conf/extra/httpd-vhosts.conf 
<ifmodule mod_expires.c> 
 ExpiresActive on 
   
     Expiresbytype image/gif "Access plus 1 days" expiresbytype image/jpeg "Access plus hours" Expires Bytype image/png "Access plus hours" expiresbytype text/css "now plus 2 hour" Expiresbytype Applicati On/x-javascript "now plus 2 hours" expiresbytype application/javascript "now plus 2 hours" expiresbytype Application/x-shockwave-flash "now plus 2 hours" expiresdefault "now plus 0 min" </IfModule>
   

Or use the Mod_headers module to implement:

<ifmodule mod_headers.c> 
 # htm,html,txt class file cache for one hours 
 <filesmatch "\. ( Html|htm|txt) $ "> 
 header Set Cache-control" max-age=3600 " 
 </filesmatch> 

 # css, JS, SWF class file cache one weeks 
 <filesmatch "\. ( css|js|swf) $ "> 
 header Set Cache-control" max-age=604800 " 
 </filesmatch> 

 # jpg,gif,j Peg,png,ico,flv,pdf file cache for one year 
 <filesmatch "\. ( ico|gif|jpg|jpeg|png|flv|pdf) $ "> 
 header Set Cache-control" max-age=29030400 " 
 </filesmatch>  ; 
</IfModule>

Description: The time unit here can days, hours or even min, two different methods, the above is used Mod_expires, and the following is mod_headers, to use these modules, you must have been supported in advance. How to see if support, using commands:

#/usr/local/apache2/bin/apachectl-m

2. Restart the server and verify

Apachectl-t 
Apachectl Graceful

Verify:

# curl-x127.0.0.1:80 ' http://www.123.com/static/image/common/online_admin.gif ' 
-i http/1.1 OK 
date:wed,   Oct 03:51:26 GMT 
server:apache/2.2.31 (Unix) php/5.5.38 
last-modified:tue, 03:08:36 GMT 
ETag: "46891b-16b-5341ab0597500" 
Accept-ranges:bytes 
content-length:363 
cache-control:max-age=86400 
expires:thu, Oct 2016 03:51:2 6 GMT 
Content-type:image/gif
Eight, Apache configuration anti-theft chain

If your site has a lot of beautiful pictures, such as your site domain name www.123.com, the image address is www.123.com/image/111.jpg, then others can directly put this address on his own site, his users can directly from his site to view this picture, And the actual picture is accessed from your website, the resulting bandwidth consumption for you do not have any meaning, should be limited to these pictures, generally on the third party site, strictly forbidden to visit your site pictures, how to configure it.

1. Configure the anti-theft chain

# vim/usr/local/apache2/conf/extra/httpd-vhosts.conf 
setenvifnocase Referer "^http://.*\.123\.com" Local_ref C3/>setenvifnocase Referer ". *\.abc\.com" Local_ref 
setenvifnocase Referer "^$" local_ref <filesmatch 
"\. ( Txt|doc|mp3|zip|rar|jpg|gif) "> 
 Order allow,deny allow from 
 env=local_ref 
</filesmatch>

Description: In this section of the configuration involves a noun referer, is actually the last visit website link. Configuration Referer is based on the source link is limited, if the source link is not what we want, the direct refusal, this is the principle of anti-theft chain. Of course, not only pictures, mp3, RAR, zip and other files are also supported. In the above configuration, the default is referer in addition to the defined list, and others are rejected.

IX. Apache access control

In fact, we can control access to Apache, you can set a whitelist or blacklist. Before the change httpd.conf time has seen the allow,deny these two keywords, first look at the rules of allow and deny.

1, Example 1

Order Deny,allow deny from all to 
127.0.0.1

Our judgment is based on the following: Look at the back of the order, which is before, which in the latter if the deny before, then you need to see the deny from this sentence, and then see the let from this rule is a match, whether it is a deny before or allow before, will take effect.

2, Example 2

Order Allow,deny deny from all to 
127.0.0.1

This will deny all, 127.0.0.1 will also be denied. Because the order is allow then deny, although the start Allow 127, but later rejected it.

3, Example 3

Order Allow,deny 
deny from all

The rules above indicate that none of them can be passed.

4, Example 4

Order deny,allow 
deny 
from the rule above indicates that all are not able to pass.  Order 

Deny,allow is 
only sequential, there is no specific rule, it means that all can pass (default), because allow is at the end. 

Order Allow,deny 
This means that all is not accessible (default), because Deny is at the end.

5. For a directory limit

For example, this directory is very important, only allow our company's IP access, of course, this directory can be the site root directory, that is, the entire site.

<Directory/usr/local/apache2/htdocs> 
 Order Deny,allow deny from all to
 127.0.0 .1 </Directory>

6, the URL to the request to limit

<filesmatch "(. *) admin (. *)" > 
 Order deny,allow deny from all to
 127.0.0.1 
   </filesmatch>

The FilesMatch syntax is used here to indicate the meaning of the match.

7. Verification

# curl-x192.168.0.8:80 Www.123.com/admin.php-I
http/1.1 403 Forbidden
date:wed, Oct 2016 06:24:5 4 GMT
server:apache/2.2.31 (Unix) php/5.5.38
content-type:text/html; charset=iso-8859-1
# curl-x127.0.0.1:80 Www.123.com/admin.php-I 
http/1.1 401 Authorization Required 
date:wed, Oct 2016 06:2  5:03 GMT 
server:apache/2.2.31 (Unix) php/5.5.38 
www-authenticate:basic realm= "Please input you acount." 
content-type:text/html; charset=iso-8859-1

10. Prohibit parsing PHP

A directory is forbidden to parse PHP, this is very useful, we do the site security, this use a lot of, such as some directories can upload files, in order to avoid uploading files have Trojan, so we prohibit the directory below the access to parse PHP.

1. Configure Prohibit parsing PHP

<Directory/usr/local/apache2/htdocs/data> 
 Php_admin_flag engine off
 <filesmatch "(. *) PHP"  ;        
 Order Deny,allow 
 Deny from all
 </filesmatch> 
</Directory>

Description: Php_admin_flag engine off this statement is to prohibit parsing PHP control statements, but this configuration is not enough, because this configuration after the user can still access the PHP file, but not resolved, but can download, the user download PHP files is not appropriate, Therefore, it is necessary to prohibit again.

11. prohibit the designation of User_agent

User_agent is called the browser logo, the current mainstream browser has IE, Chrome, Firefox, 360, iphone Safari, Android phone, Baidu search engine, Google search engine and so many, Each browser has a corresponding user_agent. To avoid the innocent consumption of bandwidth caused by some useless search engines or crawlers.

<ifmodule mod_rewrite.c> 
 rewriteengine on 
 rewritecond%{http_host} ^www.abc.com$ [OR] 
 Rew Ritecond%{http_host} ^www.abcd.com$ 
 rewriterule ^/(. *) $ http:<span>//www.123.com/$1 [R=301,L] 

 Rew Ritecond%{http_user_agent} ". *firefox.*" [Nc,or] 
 Rewritecond%{http_user_agent} ". *tomato Bot.*" [NC] 
 R Ewriterule. *-[F]
</IfModule>

It is also possible to use the rewrite module to restrict the specified user_agent. In this example, Rewriterule. *–[f] can be directly forbidden, Rewritecond is matched with User_agent, NC means case insensitive, or indicates or joins the next condition. If we want to limit Baidu's search engine, you can add a rule like this:

Rewritecond%{http_user_agent} ^.*baiduspider/2.0.* [NC] 
rewriterule. *-[F]
12. Restrict a directory

We can allow and deny to go to a subdirectory in the root directory of the site now, of course, this rewrite can also be implemented, configured as follows:

 <ifmodule mod_rewrite.c>     & nbsp Rewriteengine on      rewritecond%{request_uri} ^.*/tmp/* [NC]      rewriterule. *-[F ]   </ifmodule> 

This configuration restricts requests that contain/tmp/words.


This is Zhang original, reproduced please consciously note:
Reprint please specify from Zhang Zhenyun's personal website-Cloud code note, this address: http://www.itzcy.com/blog/1299.html
unless noted, Zhang Zhenyun's personal website-cloud-encoded note articles are original, reproduced please indicate the source and links.
Reprint Please specify the personal website from Zhang Zhenyun-Cloud Code note, this address: http://www.itzcy.com/blog/1299.html
unless noted, Zhang Zhenyun's personal website-Cloud Code note articles are original, reproduced please indicate the source and link.

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.