Home | 簡體中文 | 繁體中文 | 雜文 | 知乎專欄 | Github | OSChina 博客 | 雲社區 | 雲棲社區 | Facebook | Linkedin | 視頻教程 | 打賞(Donations) | About
知乎專欄多維度架構 微信號 netkiller-ebook | QQ群:128659835 請註明“讀者”

47.2. Module

模組的做用如下:
mod_access 	提供基于主機的訪問控制命令
mod_actions 能夠運行基于MIME類型的CGI腳本或HTTP請求方法
mod_alias 	能執行URL重定向服務
mod_asis 	使文檔能在沒有HTTP頭標的情況下被發送到客戶端
mod_auth 	支持使用存儲在文本檔案中的用戶名、口令實現認證
mod_auth_dbm 支持使用DBM檔案存儲基本HTTP認證
mod_auth_mysql 支持使用MySQL資料庫實現基本HTTP認證
mod_auth_anon 允許以匿名方式訪問需要認證的區域
mod_auth_external支持使用第三方認證
mod_autoindex 當缺少索引檔案時,自動生成動態目錄列表
mod_cern_meta 提供對元信息的支持
mod_cgi 	支持CGI
mod_dir 	能夠重定向任何對不包括尾部斜杠字元命令的請求
mod_env 	使你能夠將環境變數傳遞給CGI或SSI腳本
mod_expires 讓你確定Apache在伺服器響應請求時如何處理Expires
mod_headers 能夠操作HTTP應答頭標
mod_imap 	提供圖形映射支持
mod_include 使支持SSI
mod_info 	對伺服器配置提供了全面的描述
mod_log_agent 允許在單獨的日誌檔案中存儲用戶代理的信息
mod_log_config 支持記錄日誌
mod_log_referer 提供了將請求中的Referer頭標寫入日誌的功能
mod_mime 用來向客戶端提供有關文檔的元信息
mod_negotiation 提供了對內容協商的支持
mod_setenvif 使你能夠創建定製環境變數
mod_speling 使你能夠處理含有拼寫錯誤或大小寫錯誤的URL請求
mod_status 	允許管理員通過WEB管理Apache
mod_unique_id 為每個請求提供在非常特殊的條件下保證是唯一的標識
	

常用模組

LoadModule dir_module         modules/mod_dir.so
LoadModule mime_module        modules/mod_mime.so
LoadModule expires_module     modules/mod_expires.so
LoadModule config_log_module  modules/mod_log_config.so
LoadModule alias_module       modules/mod_alias.so
LoadModule rewrite_module     modules/mod_rewrite.so
LoadModule access_module      modules/mod_access.so
LoadModule auth_module        modules/mod_auth.so
	

47.2.1. Output a list of modules compiled into the server.

This will not list dynamically loaded modules included using the LoadModule directive.

[root@development bin]# httpd -l
Compiled in modules:
  core.c
  worker.c
  http_core.c
  mod_so.c
		

47.2.2. Core

47.2.2.1. Listen

綁定多個IP

#Listen 80
Listen 192.168.3.40:80
Listen 192.168.4.40:80
Listen 192.168.5.40:80
			

47.2.2.2. Filesystem and Webspace

ref: http://httpd.apache.org/docs/2.2/en/sections.html

Filesystem Containers

			
<Directory /var/web/dir1>
	Options +Indexes
</Directory>

<Files private.html>
	Order allow,deny
	Deny from all
</Files>

<Directory /var/web/dir1>
	<Files private.html>
		Order allow,deny
		Deny from all
	</Files>
</Directory>
			
			

Webspace Containers

			
<LocationMatch ^/private>
	Order Allow,Deny
	Deny from all
</LocationMatch>
			
			

Wildcards and Regular Expressions

			
A non-regex wildcard section that changes the configuration of all user directories could look as follows:

<Directory /home/*/public_html>
Options Indexes
</Directory>
Using regex sections, we can deny access to many types of image files at once:

<FilesMatch \.(?i:gif|jpe?g|png)$>
Order allow,deny
Deny from all
</FilesMatch>
			
			
47.2.2.2.1. Options
				
<DirectoryMatch (/var/www/logs|/var/www/logs/*)>
        Options FollowSymLinks MultiViews Indexes

        DirectoryIndex index.html

        AllowOverride AuthConfig
        Order Allow,Deny
        Allow From All

        AuthName "Logs Access"
        AuthType Basic
        AuthUserFile /etc/nagios3/htpasswd.users
        require valid-user
</DirectoryMatch>
				
				
  1. None是禁止所有

  2. Indexes 當沒有index.html 的時候列出目錄

  3. FollowSymLinks 允許符號連接,可以通過符號連接跨越DocumentRoot

  4. AllowOverride 定義是否允許各個目錄用目錄中的.htaccess覆蓋這裡設定的Options

47.2.2.3. Etag

			
<Directory /www>
	<Files ~ "\.(gif|jpe?g|png|html|css|js)$">
		FileETag INode MTime Size
	</Files>
</Directory>
			
			

47.2.2.4. 隱藏 Apache 版本信息

ServerTokens ProductOnly
ServerSignature Off
			

47.2.3. mpm

47.2.3.1. event

ThreadLimit 需要自行添加

ServerLimit 需要自行添加

			
<IfModule mpm_event_module>
    ThreadLimit			256
    ServerLimit			4096
    StartServers             4
    MinSpareThreads         75
    MaxSpareThreads        250
    ThreadsPerChild        128
    MaxRequestWorkers      4096
    MaxConnectionsPerChild   0
</IfModule>
			
			

47.2.3.2. worker

worker

# Server-pool management (MPM specific)
Include conf/extra/httpd-mpm.conf
			

conf/extra/httpd-mpm.conf

mpm_worker_module

			
<IfModule mpm_worker_module>
    ServerLimit         16
    ThreadLimit         128
    StartServers        8
    MaxClients          2048
    MinSpareThreads     64
    MaxSpareThreads     128
    ThreadsPerChild     128
    MaxRequestsPerChild 10000
</IfModule>

<IfModule mpm_worker_module>
    ServerLimit         24
    ThreadLimit         128
    StartServers        8
    MaxClients          3072
    MinSpareThreads     64
    MaxSpareThreads     128
    ThreadsPerChild     128
    MaxRequestsPerChild 10000
</IfModule>

<IfModule mpm_worker_module>
    ServerLimit         16
    ThreadLimit         256
    StartServers        8
    MaxClients          4096
    MinSpareThreads     64
    MaxSpareThreads     256
    ThreadsPerChild     256
    MaxRequestsPerChild 10000
</IfModule>

			
			
			
ServerLimit 預設是16,它決定系統最多啟動幾個httpd進程。
ThreadLimit 預設是64,
ThreadsPerChild* ServerLimit=系統支持的最大並發。
MaxClients<ThreadsPerChild* ServerLimit,MaxClients如果大於400將被限制在400.
400只是理論最大並發,實際並發就是MaxClients的值。
理論並發有什麼用我不知道。


指令說明:
        StartServers:設置伺服器啟動時建立的子進程數量。因為子進程數量動態的取決於負載的輕重,所有一般沒有必要調整這個參數。
        ServerLimit:伺服器允許配置的進程數上限。只有在你需要將MaxClients和ThreadsPerChild設置成需要超過預設值16個子進程的時候才需要使用這個指令。不要將該指令的值設置的比MaxClients 和ThreadsPerChild需要的子進程數量高。修改此指令的值必須完全停止服務後再啟動才能生效,以restart方式重啟動將不會生效。
        ThreadLimit:設置每個子進程可配置的綫程數ThreadsPerChild上限,該指令的值應當和ThreadsPerChild可能達到的最大值保持一致。修改此指令的值必須完全停止服務後再啟動才能生效,以restart方式重啟動將不會生效。
        MaxClients:用於伺服客戶端請求的最大接入請求數量(最大綫程數)。任何超過MaxClients限制的請求都將進入等候隊列。預設值是"400",16 (ServerLimit)乘以25(ThreadsPerChild)的結果。因此要增加MaxClients的時候,你必須同時增加 ServerLimit的值。筆者建議將初始值設為(以Mb為單位的最大物理內存/2),然後根據負載情況進行動態調整。比如一台4G內存的機器,那麼初始值就是4000/2=2000。
        MinSpareThreads:最小空閒綫程數,預設值是"75"。這個MPM將基于整個伺服器監視空閒綫程數。如果伺服器中總的空閒綫程數太少,子進程將產生新的空閒綫程。
        MaxSpareThreads:設置最大空閒綫程數。預設值是"250"。這個MPM將基于整個伺服器監視空閒綫程數。如果伺服器中總的空閒綫程數太多,子進程將殺死多餘的空閒綫程。MaxSpareThreads的取值範圍是有限制的。Apache將按照如下限制自動修正你設置的值:worker要求其大於等於 MinSpareThreads加上ThreadsPerChild的和。
        ThreadsPerChild:每個子進程建立的綫程數。預設值是25。子進程在啟動時建立這些綫程後就不再建立新的綫程了。每個子進程所擁有的所有線程的總數要足夠大,以便可以處理可能的請求高峰。
        MaxRequestsPerChild:設置每個子進程在其生存期內允許伺服的最大請求數量。到達MaxRequestsPerChild的限制後,子進程將會結束。如果MaxRequestsPerChild為"0",子進程將永遠不會結束。將MaxRequestsPerChild設置成非零值有兩個好處:可以防止(偶然的)內存泄漏無限進行而耗盡內存;
給進程一個有限壽命,從而有助于當伺服器負載減輕的時候減少活動進程的數量。
如果設置為非零值,筆者建議設為10000-30000之間的一個值。
         公式:
         ThreadLimit >= ThreadsPerChild
         MaxClients <= ServerLimit * ThreadsPerChild 必須是ThreadsPerChild的倍數
         MaxSpareThreads >= MinSpareThreads+ThreadsPerChild
			
			

47.2.4. Apache Log

47.2.4.1. LogLevel

日誌級別

語法:LogLevel level

可以選擇下列level,依照重要性降序排列:
emerg  緊急(系統無法使用)
alert  必須立即採取措施
crit  	致命情況
error  錯誤情況
warn  	警告情況
notice 	一般重要情況
info   普通信息
debug  調試信息
			
LogLevel crit
			

47.2.4.2. LogFormat

分割log日誌檔案

			
<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    #LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %{email}C %{nickname}C" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    #CustomLog logs/access_log common

    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    CustomLog logs/access_log combined

    #CookieLog logs/cookie_log
</IfModule>
			
			

47.2.4.3. Compressed

			
# compressed logs
$ CustomLog "|/usr/bin/gzip -c >> /var/log/access_log.gz" common
			
			

47.2.4.4. rotatelogs - Piped logging program to rotate Apache logs

rotatelogs是一個配合Apache管道日誌功能使用的簡單程序。舉例:

rotatelogs logfile [ rotationtime [ offset ]] | [ filesizeM ]

選項
logfile
它加上基準名就是日誌檔案名。如果logfile中包含’%',則它會被視為用於的strftime(3)的格式字串;否則,它會被自動加上以秒為單位的.nnnnnnnnnn尾碼。這兩種格式都表示新的日誌開始使用的時間。
rotationtime
日誌檔案回捲的以秒為單位的間隔時間
offset
相對於UTC的時差的分鐘數。如果省略,則假定為0,並使用UTC時間。比如,要指定UTC時差為-5小時的地區的當地時間,則此參數應為-300。
filesizeM
指定回捲時以兆位元組為單位的尾碼字母M的檔案大小,而不是指定回捲時間或時差。

下列日誌檔案格式字串可以為所有的strftime(3)實現所支持,見各種擴展庫對應的strftime(3)的手冊。
%A 星期名全稱(本地的)
%a 3個字元的星期名(本地的)
%B 月份名的全稱(本地的)
%b 3個字元的月份名(本地的)
%c 日期和時間(本地的)
%d 2位數的一個月中的日期數
%H 2位數的小時數(24小時制)
%I 2位數的小時數(12小時制)
%j 3位數的一年中的日期數
%M 2位數的分鐘數
%m 2位數的月份數
%p am/pm 12小時制的上下午(本地的)
%S 2位數的秒數
%U 2位數的一年中的星期數(星期天為一周的第一天)
%W 2位數的一年中的星期數(星期一為一周的第一天)
%w 1位數的星期幾(星期天為一周的第一天)
%X 時間 (本地的)
%x 日期 (本地的)
%Y 4位數的年份

CustomLog "|bin/rotatelogs /var/logs/logfile 86400" common
此配置會建立檔案"/var/logs/logfile.nnnn",其中的nnnn是名義上的日誌啟動時的系統時間(此時間總是滾動時間的倍數,可以用於cron腳本的同步)。在滾動時間到達時(在此例中是24小時以後),會產生一個新的日誌。

CustomLog "|bin/rotatelogs /var/logs/logfile 5M" common
此配置會在日誌檔案大小增長到5兆位元組時滾動該日誌。

ErrorLog "|bin/rotatelogs /var/logs/errorlog.%Y-%m-%d-%H_%M_%S 5M"
此配置會在錯誤日誌大小增長到5兆位元組時滾動該日誌,日誌檔案名尾碼會按照如下格式創建:errorlog.YYYY-mm-dd-HH_MM_SS

ErrorLog "| /usr/local/apache/bin/rotatelogs /www/logs/www.example.com/error_%Y_%m_%d_log 86400 480"
CustomLog "| /usr/local/apache/bin/rotatelogs /www/logs/www.example.com/access_%Y_%m_%d_log 86400 480" common

CustomLog "|/usr/local/httpd/bin/rotatelogs /www/logs/www.example.com/access.%Y-%m-%d.log 86400 480" combined
			

86400:表示 24小時 60*60*24

480: 表示時區偏移 8 時區等於 60*8

47.2.4.5. cronolog

cronolog

cd /usr/local/src/
wget http://cronolog.org/download/cronolog-1.6.2.tar.gz
tar zxvf cronolog-1.6.2.tar.gz
cd cronolog-1.6.2
./configure --prefix=/usr/local/cronolog
make
make install
			

CustomLog "|/usr/local/cronolog/sbin/cronolog /opt/apache/logs/access_log.%Y%m%d" combined

47.2.4.6. 日誌合併

合併多個伺服器的日誌檔案(如log1、log2、log3),並輸出到log_all中的方法是:

 $ sort -m -t " " -k 4 -o log_all log1 log2 log3
			

47.2.4.7. 日誌歸檔

30 4 * * * /usr/bin/gzip -f /www/logs/access.`date -d yesterday +%Y-%m-%d`.log
			

47.2.4.8. logger

https://www.sit.auckland.ac.nz/Logging_to_syslog_with_Apache

			
Logging to syslog with Apache

First you will need to install syslog-ng. This is the logging server that will send the log data to the syslog box.

apt-get update && apt-get install syslog-ng
syslog-ng uses a socket device to accept data from apache or whatever program is creating the logs.

Use the configuration here: Syslog-ng default config.

The first part indicates what the socket will be called and where it will live. The second part tells syslog-ng where to send the collected data. The restart syslog-ng (/etc/init.d/syslog-ng restart)l.

Configure apache's logging

Add these directives to send apache's logs via a socket to syslog

CustomLog "|/usr/bin/logger -s -t 'monitor.cs.auckland.ac.nz' -p info -u /var/log/apache_log.socket" Combined
ErrorLog "|/usr/bin/logger -s -t 'monitor.cs.auckland.ac.nz' -p err -u /var/log/apache_log.socket"
Apache will then use the logger program to send data to syslog. /var/log/apache_log.socket refers to the device that syslog-ng has created. Data sent to this device is sent over the network to the main syslog box.

Troubleshooting

It seems that apache 2.0.54-5 does not like logging to a file and to a process at the same time. In this case log entries will become re-ordered or missed out. You can use the test scripts below to check if this is happening.

Testing

Here are some useful scripts that can help with testing to make sure the logging is working as expected.

You can simulate http accesses using lynx with this command:

watch lynx -source http://monitor.cs.auckland.ac.nz/
Which will make a http request every two seconds. Or, for a better test:

for i in `seq 1 100`; do lynx -source http://monitor.cs.auckland.ac.nz/$i;sleep 3;done
The result of this test is a sequence of log entires from 1 to 100. If entries are missing or in the wrong order, you know there is a problem.
			
			

47.2.4.9. other

CustomLog "|/usr/bin/your_script" Combined
ErrorLog "|/usr/bin/your_script"
			

47.2.5. mod_access

		
<Directory /www>
  Order Allow,Deny
</Directory>

<Directory /www>
	Order Deny,Allow
	Deny from all
	Allow from apache.org
</Directory>


<Directory /www>
	Order Allow,Deny
	Allow from apache.org
	Deny from foo.apache.org
</Directory>
		
		
A (partial) domain-name
Example: Allow from apache.org

A full IP address
Example: Allow from 10.1.2.3

A partial IP address
Example: Allow from 10.1

A network/netmask pair
Example: Allow from 10.1.0.0/255.255.0.0

A network/nnn CIDR specification
Example: Allow from 10.1.0.0/16
		
		
<DirectoryMatch (/usr/share/nagios3/htdocs|/usr/lib/cgi-bin/nagios3|/etc/nagios3/stylesheets)>
        Options FollowSymLinks

        DirectoryIndex index.html

        AllowOverride AuthConfig
        Order Allow,Deny
        Allow From All

        AuthName "Nagios Access"
        AuthType Basic
        AuthUserFile /etc/nagios3/htpasswd.users
        # nagios 1.x:
        #AuthUserFile /etc/nagios/htpasswd.users
        require valid-user
</DirectoryMatch>
		
		

Apache httpd 2.4.x

		
    <Directory "/www/www.example.com">
	        Options Indexes FollowSymLinks
	        AllowOverride None
	        Require all granted
    </Directory>
		
		

47.2.6. VirtualHost

conf/extra/httpd-vhosts.conf

or

/etc/httpd/conf.d/vhost.conf

		
NameVirtualHost *:80

<VirtualHost *:80>
    ServerAdmin webmaster@dummy-host.example.com
    DocumentRoot "/usr/local/httpd-2.2.14/docs/dummy-host.example.com"
    ServerName dummy-host.example.com
    ServerAlias www.dummy-host.example.com
    ErrorLog "logs/dummy-host.example.com-error_log"
    CustomLog "logs/dummy-host.example.com-access_log" common
</VirtualHost>
		
		

47.2.6.1. ServerName/ServerAlias

ServerName dummy-host.example.com
ServerAlias www.dummy-host.example.com
			

47.2.6.2. rotatelogs

CustomLog "|/usr/local/httpd/bin/rotatelogs /www/logs/www.example.com/access.%Y-%m-%d.log 86400 480" combined
ErrorLog "|/usr/local/httpd/bin/rotatelogs /www/logs/www.example.com/error.%Y-%m-%d.log 86400 480"
			

47.2.7. Alias / AliasMatch

		
Alias /image /ftp/pub/image
AliasMatch ^/icons(.*) /usr/local/apache/icons$1
		
		
		
cat /etc/httpd/conf.d/logs.conf

Alias /logs "/www/logs"

<Directory "/www/logs">
   Options FollowSymLinks MultiViews Indexes
   AllowOverride None
   Order allow,deny
   Allow from all
#  Order deny,allow
#  Deny from all
#  Allow from 127.0.0.1
#   AuthName "Logs Access"
#   AuthType Basic
#   AuthUserFile /etc/httpd/htpasswd.users
#   Require valid-user
</Directory>
		
		

47.2.8. Redirect / RedirectMatch

Redirect

		
Redirect /service http://foo2.example.com/service
Redirect permanent /one http://example.com/two
Redirect 303 /three http://example.com/other
		
		

RedirectMatch

RedirectMatch (.*)\.gif$ http://www.domain.com$1.jpg
		
		
<VirtualHost *:80>
     ServerName www.old.com
     DocumentRoot /path/to/htdocs
     ......
     <Directory "/path/to/htdocs">
         RedirectMatch ^/(.*)$ http://www.new.com/$1
     </Directory>
</VirtualHost>
		
		

47.2.9. Rewrite

Rewrite 需要 AllowOverride All

		
<Directory "/www">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.2/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
    #AllowOverride None
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
    Order allow,deny
    Allow from all

</Directory>
		
		

47.2.9.1. R=301

RewriteEngine on
RewriteCond %{HTTP_HOST} ^x.x.x.x [NC]
RewriteRule ^/(.*)$ http://www.example.com/$1 [L,R=301]

			

例 47.3. R=301

				
<VirtualHost *:80>
	ServerAdmin webmaster@example.com
	ServerName www.example.com
	ServerAlias www.second.com

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^www.example.com [NC]
    RewriteRule ^/(.*)$ http://www.other.com/$1 [L,R=301]
    RewriteCond %{HTTP_HOST} ^www.second.com [NC]
    RewriteRule ^/(.*)$ http://www.other.com/$1 [L,R=301]
</VirtualHost>
				
				

47.2.9.2. Rewrite + JkMount

JkMount 與 Rewrite 同時使用時

RewriteRule ^/communtiy/top/(.*)$ /community.do?method=activeContent&id=$1 [PT]

後面用[PT]

47.2.9.3. Apache redirect domain.com to www.domain.com

			
$ vi .htaccess
RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain\.com
RewriteRule ^(.*)$ http://www.domain.com/$1 [R=permanent,L]
			
			

47.2.9.4. 正則匹配副檔名

			
<VirtualHost *:80>
    ServerAdmin webmaster@example.com
    DocumentRoot "/www/www.example.com/images"
    ServerName images.example.com
    RewriteEngine On
    RewriteRule ^(.+)(jpg|gif|bmp|jpeg|ico|png|css)$ http://images.other.com/$1$2 [R]
    ErrorLog "logs/images.example.com-error.log"
</VirtualHost>
			
			
			
<VirtualHost *:80>
	ServerAdmin webmaster@example.com
	ServerName images.example.com
	RewriteEngine On
	RewriteCond %{HTTP_HOST} ^images.example.com [NC]
	RewriteRule ^/(.*) http://images.other.com/$1 [L]
	CustomLog "|/usr/local/httpd/bin/rotatelogs /www/logs/images/access.%Y-%m-%d.log 100M" common
</VirtualHost>
			
			

47.2.10. Proxy

		
ProxyRequests Off

<Proxy *>
	Order deny,allow
	Allow from all
</Proxy>
ProxyPass / http://your.domain.com:8080/
ProxyPassReverse / http://your.domain.com:8080/
		
		

47.2.10.1. Reverse proxy

/etc/httpd/conf.d/rails.conf

			
Listen 8080
ProxyRequests Off
<Proxy balancer://cluster>
	BalancerMember http://127.0.0.1:3001
	BalancerMember http://127.0.0.1:3002
	BalancerMember http://127.0.0.1:3003
	BalancerMember http://127.0.0.1:3004
	BalancerMember http://127.0.0.1:3005
</Proxy>

<VirtualHost *:8080>
	ServerName www.example.com:8080
	DocumentRoot /var/www/project/public
	ProxyPass /images !
	ProxyPass /stylesheets !
	ProxyPass /javascripts !
	ProxyPass / balancer://cluster/
	ProxyPassReverse / balancer://cluster/
	ProxyPreserveHost on
</VirtualHost>
			
			

47.2.11. Deflate

mod_deflate

httpd.conf中中加入下列語句:

			
<IfModule mod_deflate.c>
	SetOutputFilter DEFLATE
	DeflateCompressionLevel 9
	AddOutputFilterByType DEFLATE text/html text/plain text/xml application/x-httpd-php
	AddOutputFilter DEFLATE txt css js
	SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary
	SetEnvIfNoCase Request_URI \.(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
	SetEnvIfNoCase Request_URI \.pdf$ no-gzip dont-vary
	DeflateFilterNote Input input_info
	DeflateFilterNote Output output_info
	DeflateFilterNote Ratio ratio_info
	LogFormat '"%r" %{output_info}n/%{input_info}n (%{ratio_info}n%%)' deflate
	CustomLog logs/deflate_log.log deflate
</IfModule>
			
			

對目錄/usr/local/apache/htdocs有效

			
<Directory "/usr/local/apache/htdocs">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
	SetOutputFilter DEFLATE
	DeflateCompressionLevel 9
	AddOutputFilterByType DEFLATE text/html text/plain text/xml application/x-httpd-php
	AddOutputFilter DEFLATE txt css js
	SetEnvIfNoCase Request_URI \
	\.(?:gif|jpe?g|png)$ no-gzip dont-vary
</Directory>
			
			

			
<Location />
	AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript
	AddOutputFilterByType DEFLATE application/javascript application/x-javascript application/x-httpd-php
	AddOutputFilter DEFLATE txt css js
	SetOutputFilter DEFLATE
</Location>
			
			

Log定義

DeflateFilterNote Input instream   # 未壓縮前
DeflateFilterNote Output outstream # 壓縮後
DeflateFilterNote Ratio ratio   # 百分比
LogFormat '"%r" %{outstream}n/%{instream}n (%{ratio}n%%)' deflate # 格式定義

CustomLog logs/deflate_log.log deflate # 日誌位置
CustomLog "|/usr/local/httpd/bin/rotatelogs /www/logs/deflate.%Y-%m-%d.log 86400 480" deflate # 分割日誌位置
			

47.2.11.1. 測試 gzip,deflate 模組

telnet www.bg7nyt.cn 80
GET /index.html HTTP/1.0
Host: www.bg7nyt.cn
Accept-Encoding: gzip,deflate
			

你看到的是亂碼,而不是HTML.

curl -H Accept-Encoding:gzip,defalte http://www.example.com/index.html | gunzip
			

gunzip 可以解壓壓縮內容

47.2.12. Expires

		
ExpiresActive On
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/x-icon "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/html "access plus 30 minutes"
ExpiresByType text/css  "access plus 30 minutes"
ExpiresByType text/js   "access plus 30 minutes"
ExpiresByType application/x-javascript   "access plus 30 minutes"
ExpiresByType application/x-shockwave-flash     "access plus 30 minutes"
		
		

47.2.12.1. FilesMatch

			
<FilesMatch “\.(ico|jpg|jpeg|png|gif|js|css|swf|html|htm|gzip)$”>
	ExpiresActive on
	ExpiresDefault “access plus 2 hours”
</FilesMatch>
			
			

47.2.12.2. Cache-Control

			
<FilesMatch "\.(gif|jpe?g|png|ico|css|js|swf)$">
	Header set Cache-Control “max-age=1800, public”
	Header set Cache-Control "s-maxage=600"
</FilesMatch>
			
			

max-age 針對瀏覽器推送緩存時間

s-maxage 針對代理伺服器推送緩存時間

47.2.12.3. ETag

			
<FilesMatch "\.(gif|jpe?g|png|ico|css|js|swf)$">
	FileETag none
</FilesMatch>

<FilesMatch "\.(gif|jpe?g|png|ico|css|js|swf)$">
	FileETag MTime
</FilesMatch>
			
			

禁用ETag, FileETag none

INode 使用檔案i-node 做為 etag

MTime 使用修改時間做為etag

Size 使用檔案尺寸做為etag

All 相當於 FileETag INode MTime Size

47.2.13. Cache

htcacheclean -- program for cleaning the disk cache.

47.2.13.1. mod_disk_cache

			
<IfModule mod_cache.c>
    CacheDefaultExpire 86400
    <ifModule mod_disk_cache.c>
        CacheEnable disk /
        CacheRoot /tmp/apacheCache
        CacheDirLevels 5
        CacheDirLength 5
        CacheMaxFileSize 1048576
        CacheMinFileSize 10
    </ifModule mod_disk_cache.c>
</IfModule mod_cache.c>
			
			

47.2.13.2. mod_mem_cache

			
<IfModule mod_cache.c>
    <ifModule mod_mem_cache.c>
        CacheEnable mem /
        MCacheMaxObjectCount 20000
        MCacheMaxObjectSize 1048576
        MCacheMaxStreamingBuffer 65536
        MCacheMinObjectSize 10
        MCacheRemovalAlgorithm GDSF
        MCacheSize 131072
    </ifModule mod_disk_cache.c>
</IfModule mod_cache.c>
			
			

47.2.14. usertrack

跟蹤用戶信息

跟蹤用戶的cookie,使用log日誌檔案記錄用戶的cookie

LoadModule usertrack_module modules/mod_usertrack.so

CookieTracking on
CookieDomain .example.com
CookieExpires "10 years"
CookieStyle Cookie

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %{cookie}n" combined
		

47.2.15. Charset

Default charset

AddCharset UTF-8 .html

AddType 'text/html; charset=UTF-8' html

AddDefaultCharset UTF-8
		

Files match

		
<FilesMatch "\.(htm|html|css|js)$">
	ForceType 'text/html; charset=UTF-8'
</FilesMatch>

<FilesMatch "\.(htm|html|css|js)$">
	AddDefaultCharset UTF-8
</FilesMatch>
		
		

Changing the occasional file

		
<Files "example.html">
	AddCharset UTF-8 .html
</Files>

<Files "example.html">
	ForceType 'text/html; charset=UTF-8'
</Files>
		
		

47.2.16. Dir

		
<IfModule dir_module>
    DirectoryIndex index.html index.php
</IfModule>
		
		

47.2.17. Includes

		
<Directory "/www">
	Options Indexes FollowSymLinks +Includes
</Directory>
		
		
		
<IfModule mime_module>
	AddType text/html .shtml
    AddOutputFilter INCLUDES .shtml
</IfModule>
		
		

47.2.18. Apache Status

開啟Apache的status模組,需要修改httpd.conf,增加以下配置段:

		
ExtendedStatus On
<Location /server-status>
  SetHandler server-status
  Order deny,allow
  Deny from all
  Allow from 125.76.229.113
</Location>
		
		

http://www.domain.com/server-status

Automatic Updates

http://your.server.name/server-status?refresh=N
		
http://localhost/server-status?auto
		

擴展狀態,提供更詳細的信息

ExtendedStatus On
		

47.2.19. Mod Perl

ref: http://search.cpan.org/~agrundma/Catalyst-Engine-Apache-1.07/lib/Catalyst/Engine/Apache2/MP20.pm

$ sudo apt-get install libapache2-mod-perl2 $ sudo apt-get install libcatalyst-engine-apache-perl
$ sudo vi /etc/apache2/sites-available/catalyst.conf
		

例 47.4. mod_perl.conf

			
PerlSwitches -I/var/www/MyApp/lib
# Preload your entire application
PerlModule MyApp

<VirtualHost 192.168.245.129:80>
        ServerName 192.168.245.129
        DocumentRoot /var/www/MyApp/root

        <Directory /var/www/MyApp/root>
	        Options Indexes FollowSymLinks
	        AllowOverride None
	        Order allow,deny
	        Allow from all
        </Directory>

        # If the server is started as:
        #       httpd -X -D PERLDB
        # then debugging will be turned on
#       <IfDefine PERLDB>
#               PerlRequire conf/db.pl
#               <Location />
#                       PerlFixupHandler Apache::DB
#               </Location>
#       </IfDefine>

        <Location />
                SetHandler modperl
                PerlResponseHandler MyApp
        </Location>

        Alias /static /var/www/MyApp/root/static
        <Location /static>
                SetHandler default-handler
        </Location>
</VirtualHost>
			
			

db.pl

		
use APR::Pool ();
use Apache::DB ();
Apache::DB->init();
		
		

enable site

$ sudo a2ensite mod_perl.conf
$ sudo /etc/init.d/apache2 restart
		

47.2.20. mod_pagespeed -

https://developers.google.com/speed/pagespeed/mod

47.2.21. Module FAQ

	 	
[root@srv-2 modules]# /etc/init.d/httpd start
Starting httpd: Syntax error on line 358 of /etc/httpd/conf/httpd.conf:
Invalid command 'Order', perhaps mis-spelled or defined by a module not included
in the server configuration
[FAILED]
LoadModule access_module /etc/httpd/modules/mod_access.so
LoadModule auth_module /etc/httpd/modules/mod_auth.so
[root@srv-2 modules]# /etc/init.d/httpd start
Starting httpd: Syntax error on line 368 of /etc/httpd/conf/httpd.conf:
Invalid command 'UserDir', perhaps mis-spelled or defined by a module not includ
ed in the server configuration
[FAILED]
LoadModule userdir_module /etc/httpd/modules/mod_userdir.so
[root@srv-2 modules]# /etc/init.d/httpd start
Starting httpd: Syntax error on line 396 of /etc/httpd/conf/httpd.conf:
Invalid command 'DirectoryIndex', perhaps mis-spelled or defined by a module not
included in the server configuration
[FAILED]
LoadModule dir_module /etc/httpd/modules/mod_dir.so
[root@srv-2 modules]# /etc/init.d/httpd start
Starting httpd: Syntax error on line 419 of /etc/httpd/conf/httpd.conf:
Invalid command 'TypesConfig', perhaps mis-spelled or defined by a module not in
cluded in the server configuration
[FAILED]
LoadModule mime_module /etc/httpd/modules/mod_mime.so
[root@srv-2 modules]# /etc/init.d/httpd start
Starting httpd: Syntax error on line 491 of /etc/httpd/conf/httpd.conf:
Invalid command 'LogFormat', perhaps mis-spelled or defined by a module not incl
uded in the server configuration
[FAILED]
LoadModule log_config_module /etc/httpd/modules/mod_log_config.so
[root@srv-2 modules]# /etc/init.d/httpd start
Starting httpd: Syntax error on line 555 of /etc/httpd/conf/httpd.conf:
Invalid command 'Alias', perhaps mis-spelled or defined by a module not included
in the server configuration
[FAILED]
LoadModule alias_module /etc/httpd/modules/mod_alias.so
[root@srv-2 modules]# /etc/init.d/httpd start
Starting httpd: Syntax error on line 582 of /etc/httpd/conf/httpd.conf:
Invalid command 'SetEnvIf', perhaps mis-spelled or defined by a module not inclu
ded in the server configuration
[FAILED]
LoadModule setenvif_module /etc/httpd/modules/mod_setenvif.so
[root@srv-2 modules]# /etc/init.d/httpd start
Starting httpd: Syntax error on line 636 of /etc/httpd/conf/httpd.conf:
Invalid command 'IndexOptions', perhaps mis-spelled or defined by a module not i
ncluded in the server configuration
[FAILED]
LoadModule autoindex_module /etc/httpd/modules/mod_autoindex.so
[root@srv-2 modules]# /etc/init.d/httpd start
Starting httpd: Syntax error on line 784 of /etc/httpd/conf/httpd.conf:
Invalid command 'LanguagePriority', perhaps mis-spelled or defined by a module n
ot included in the server configuration
[FAILED]
LoadModule negotiation_module /etc/httpd/modules/mod_negotiation.so
[root@srv-2 modules]# /etc/init.d/httpd start
Starting httpd:                                            [  OK  ]
[root@srv-2 modules]#
	 	
	 	

47.2.22. mod_setenvif

屏蔽爬蟲

		
<directory "/www/example.com">
    Order allow,deny
    Allow from all
    BrowserMatchNoCase "iaskspider" badguy
    BrowserMatchNoCase "QihooBot" badguy
    BrowserMatchNoCase "larbin" badguy
    BrowserMatchNoCase "iearthworm" badguy
    BrowserMatchNoCase "Outfoxbot" badguy
    BrowserMatchNoCase "lanshanbot" badguy
    BrowserMatchNoCase "Arthur" badguy
    BrowserMatchNoCase "InfoPath" badguy
    BrowserMatchNoCase "DigExt" badguy
    BrowserMatchNoCase "Embedded" badguy
    BrowserMatchNoCase "EmbeddedWB" badguy
    BrowserMatchNoCase "Wget" badguy
    BrowserMatchNoCase "CNCDialer" badguy
    BrowserMatchNoCase "LWP::Simple" badguy
    BrowserMatchNoCase "WPS" badguy
    deny from env=badguy
</directory>
		
		

屏蔽下載

BrowserMatch "NetAnt" badguy
BrowserMatch "GetRight" badguy
BrowserMatch "JetCar" badguy
BrowserMatch "Mass Downloader" badguy
BrowserMatch "ReGet" badguy
BrowserMatch "DLExpert" badguy
BrowserMatch "FlashGet" badguy
BrowserMatch "Offline Explorer" badguy
BrowserMatch "Teleport" badguy
...........

order deny,allow
deny from env=badguy
allow from all
		

47.2.23. PHP 程序安全問題 php_admin_value

php 安全

		
php_admin_value open_basedir /var/www/htdocs/
		
		
		
<IfModule mod_php5.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag engine on
</IfModule>
<IfModule mod_php4.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag engine on
</IfModule>
		
		

47.2.24. mod_spdy

mod_spdy 是用於 Apache HTTP 伺服器的 Google SPDY 協議實現模組,

SPDY並不是一種用於替代HTTP的協議,而是對HTTP協議的增強。新協議的功能包括數據流的多路復用、請求優先順序,以及HTTP包頭壓縮。谷歌已經開發一個網絡伺服器原型機,以及支持SPDY協議的Chrome瀏覽器版本。

https://code.google.com/p/mod-spdy/