哪一天 哪一天 我有吃有穿有住有钱 不再流浪 流浪
标签类目:apache

Apache ab压力测试

今天研究了一下ab压力测试
看到一篇不错的文章, 原作者不详

工具 AB(apache benchmark).在APACHE的bin目录下。

格式: ./ab [options] [http://]hostname[:port]/path

参数:

-n requests Number of requests to perform

//在测试会话中所执行的请求个数。默认时,仅执行一个请求

-c concurrency Number of multiple requests to make

//一次产生的请求个数。默认是一次一个。

-t timelimit Seconds to max. wait for responses

//测试所进行的最大秒数。其内部隐含值是-n 50000。它可以使对服务器的测试限制在一个固定的总时间以内。默认时,没有时间限制。

-p postfile File containing data to POST

//包含了需要POST的数据的文件.

-T content-type Content-type header for POSTing

//POST数据所使用的Content-type头信息。

-v verbosity How much troubleshooting info to print

//设置显示信息的详细程度 – 4或更大值会显示头信息, 3或更大值可以显示响应代码(404, 200等), 2或更大值可以显示警告和其他信息。 -V 显示版本号并退出。

-w Print out results in HTML tables

//以HTML表的格式输出结果。默认时,它是白色背景的两列宽度的一张表。

-i Use HEAD instead of GET

// 执行HEAD请求,而不是GET。

-x attributes String to insert as table attributes

//

-y attributes String to insert as tr attributes

//

-z attributes String to insert as td or th attributes

//

-C attribute Add cookie, eg. ‘Apache=1234. (repeatable)

//-C cookie-name=value 对请求附加一个Cookie:行。 其典型形式是name=value的一个参数对。此参数可以重复。

-H attribute Add Arbitrary header line, eg. ‘Accept-Encoding: gzip’

Inserted after all normal header lines. (repeatable)

-A attribute Add Basic WWW Authentication, the attributes

are a colon separated username and password.

-P attribute Add Basic Proxy Authentication, the attributes

are a colon separated username and password.

//-P proxy-auth-username:password 对一个中转代理提供BASIC认证信任。用户名和密码由一个:隔开,并以base64编码形式发送。无论服务器是否需要(即, 是否发送了401认证需求代码),此字符串都会被发送。

-X proxy:port Proxyserver and port number to use

-V Print version number and exit

-k Use HTTP KeepAlive feature

-d Do not show percentiles served table.

-S Do not show confidence estimators and warnings.

-g filename Output collected data to gnuplot format file.

-e filename Output CSV file with percentages served

-h Display usage information (this message)

//-attributes 设置 属性的字符串. 缺陷程序中有各种静态声明的固定长度的缓冲区。另外,对命令行参数、服务器的响应头和其他外部输入的解析也很简单,这可能会有不良后果。它没有完整地实现 HTTP/1.x; 仅接受某些’预想’的响应格式。 strstr(3)的频繁使用可能会带来性能问题,即, 你可能是在测试ab而不是服务器的性能。

参数很多,一般我们用 -c 和 -n 参数就可以了. 例如:

./ab -c 1000 -n 1000 http://127.0.0.1/index.php

这个表示同时处理1000个请求并运行1000次index.php文件.

#/usr/local/xiaobai/apache2054/bin/ab -c 1000 -n 1000 http://127.0.0.1/index.html.zh-cn.gb2312

This is ApacheBench, Version 2.0.41-dev <$Revision: 1.121.2.12 $> apache-2.0

Copyright (c) 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/

Copyright (c) 1998-2002 The Apache Software Foundation, http://www.apache.org/

Benchmarking 127.0.0.1 (be patient)

Completed 100 requests

Completed 200 requests

Completed 300 requests

Completed 400 requests

Completed 500 requests

Completed 600 requests

Completed 700 requests

Completed 800 requests

Completed 900 requests

Finished 1000 requests

Server Software: Apache/2.0.54

//平台apache 版本2.0.54

Server Hostname: 127.0.0.1

//服务器主机名

Server Port: 80

//服务器端口

Document Path: /index.html.zh-cn.gb2312

//测试的页面文档

Document Length: 1018 bytes

//文档大小

Concurrency Level: 1000

//并发数

Time taken for tests: 8.188731 seconds

//整个测试持续的时间

Complete requests: 1000

//完成的请求数量

Failed requests: 0

//失败的请求数量

Write errors: 0

Total transferred: 1361581 bytes

//整个场景中的网络传输量

HTML transferred: 1055666 bytes

//整个场景中的HTML内容传输量

Requests per second: 122.12 [#/sec] (mean)

//大家最关心的指标之一,相当于 LR 中的 每秒事务数 ,后面括号中的 mean 表示这是一个平均值

Time per request: 8188.731 [ms] (mean)

//大家最关心的指标之二,相当于 LR 中的 平均事务响应时间 ,后面括号中的 mean 表示这是一个平均值

Time per request: 8.189 [ms] (mean, across all concurrent requests)

//每个请求实际运行时间的平均值

Transfer rate: 162.30 [Kbytes/sec] received

//平均每秒网络上的流量,可以帮助排除是否存在网络流量过大导致响应时间延长的问题

Connection Times (ms)

min mean[+/-sd] median max

Connect: 4 646 1078.7 89 3291

Processing: 165 992 493.1 938 4712

Waiting: 118 934 480.6 882 4554

Total: 813 1638 1338.9 1093 7785

//网络上消耗的时间的分解,各项数据的具体算法还不是很清楚

Percentage of the requests served within a certain time (ms)

50% 1093

66% 1247

75% 1373

80% 1493

90% 4061

95% 4398

98% 5608

99% 7368

100% 7785 (longest request)

//整个场景中所有请求的响应情况。在场景中每个请求都有一个响应时间,其中50%的用户响应时间小于1093 毫秒,60% 的用户响应时间小于1247 毫秒,最大的响应时间小于7785 毫秒

由于对于并发请求,cpu实际上并不是同时处理的,而是按照每个请求获得的时间片逐个轮转处理的,所以基本上第一个Time per request时间约等于第二个Time per request时间乘以并发请求数

Windows下Apache报错:通常每个套接字地址(协议/网络地址/端口)只允许使用一次

刚才sanp在windows平台下配置apache
报了如下一个错误:

(OS 10048)通常每个套接字地址(协议/网络地址/端口)只允许使用一次。 : make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down

导致这个问题的原因如下:

1: 可能是本机同时安装了IIS,占用了80端口,关闭IIS重启Apache
2: 可能是本机开着迅雷或者其他软件占用了80端口,试着关闭相关软件

sanp是因为本机开着迅雷导致这个问题, 关闭了就正常了.

Apache下设置404错误页面

Apache下设置404错误页面

为Apache Server设置 404错误页面的方法芗虻ィ?恍柙?htaccess 文件中加入如下内容即可:

CODE:
ErrorDocument 404 /404.html
[Copy to clipboard]

在“通过HTTP状态码查看搜索引擎蜘蛛如何爬行你的网站”一文中,我介绍了一些经常涉及到的HTTP状态码及含义,譬如大家经常探讨并且与本文相关的Http状态码:

404:服务器找不到指定的资源,请求的网页不存在(譬如浏览器请求的网页被删除或者移位,但不排除日后该链接有效的可能性);
410:请求的网页不存在(注意:410表示永久性,而404表示临时性);
200:服务器成功返回请求的网页;
301:网址永久性重定向
302:网址临时性重定向

注意:大部分搜索引擎将“404”与“410”状态同等对待,如Google。(参见Matt Cutts的说明)

对HTTP404状态码的理解

HTTP 404 错误意味着链接指向的网页不存在,即原始网页的URL失效,这种情况经常会发生,很难避免,比如说:网页URL生成规则改变、网页文件更名或移动位置、导 入链接拼写错误等,导致原来的URL地址无法访问;当Web 服务器接到类似请求时,会返回一个404 状态码,告诉浏览器要请求的资源并不存在。但是,Web服务器默认的404错误页面,无论Apache还是IIS,均十分简陋、呆板且对用户不友好,无法 给用户提供必要的信息以获取更多线索,无疑这会造成用户的流失。

因此,很多网站均使用自定义404错误的方式以提供用户体验避免用户流失。一般而言,自定义404页面通用的做法是在页面中放置网站快速导航链接、搜索框以及网站提供的特色服务,这样可以有效的帮助用户访问站点并获取需要的信息。

HTTP404对SEO的影响

自定义404错误页面是提供用户体验的很好的做法,但在应用过程中往往并未注意到对搜索引擎的影响,譬如:错误的服务器端配置导致返回“200”状态码 或自定义404错误页面使用Meta Refresh导致返回“302”状态码。正确设置的自定义404错误页面,不仅应当能够正确地显示,同时,应该返回“404”错误代码,而不是 “200”或“302”。虽然对访问的用户而言,HTTP状态码究竟是“404”还是“200”来说并没有什么区别,但对搜索引擎而言,这则是相当重要 的。

(一)自定义404错误页返回“200”状态码

当搜索引擎蜘蛛在请求某个URL时得到“404”状态回应时,即 知道该URL已经失效,便不再索引该网页,并向数据中心反馈将该URL表示的网页从索引数据库中删除,当然,删除过程有可能需要很长时间;而当搜索引擎得 到“200”状态回应时,则会认为该url是有效的,便会去索引,并会将其收录到索引数据库,这样的结果便是这两个不同的url具有完全相同的内容:自定 义404错误页面的内容,这会导致出现复制网页问题。对搜索引擎而言,特别是Google,不但很难获得信任指数TrustRank,也会大大降低 Google对网站质量的评定。(为什么会出现返回“200”状态码的情况??请参看下面内容“自定义404错误页面的基本原则”)

我一直在使用Google Sitemap,当我们提交XML格式网站地图文件时,Google会验证我们的身份以确保是网站合法的管理者。验证方式有两种:上传指定名称的html 页到网站根目录或者在网页meta区域添加一个标识身份的meta标签。我通常是使用上传html网页的方式,但Google却提示我网站根目录下找不到 这个网页(实际上我已上传,并且通过浏览器可以访问),这是一个很可怕的问题,见图:

(二)自定义404错误页使用Meta Refresh返回“302”状态码

常常看到许多网站的自定义404错误页面采取类似这样的形式:首先显示一段错误信息,然后,通过Meta Refresh将页面跳转到网站首页、网页地图或其他类似页。根据具体实现方式不同,这类404页面可能返回“200”状态码,也可能返回“302”,但 不论哪种,从SEO技术角度看,均不是一种合适的选择。

对“200”状态的情况我们上面已经谈过,那么,当404页面返回“302” 时,搜索引擎会怎么对待呢?从理论上说,对“302”错误,搜索引擎认为该网页是存在的,只不过临时改变了地址,仍然会索引收录该页,这样,同样会出现类 似于“200”状态码时的重复文本问题;其次,以google为代表的主流搜索引擎对302重定向的适用范围要求越来越严格,这类不当使用302重定向的 情况存在很大的风险。

确保自定义404错误页面能够返回“404”状态码

在自定义404错误页面设置完毕后,一定要检查一下其是不是能够正确地返回“404”状态码。可以使用Server Header检查工具,输入一个不存在网页的url,查看一下HTTP Header的返回情况,确信其返回的是“404 Not found”。

404错误的处理方式
(一)定制404错误页面的基本原则

首先应明确的是,404错误应工作在服务器级而不是网页级。对定制使用动态页面如PHP脚本类型的404页时,必须确保在PHP执行前服务器已经顺利地 送出“404”状态码,不然,一旦执行到了ISAPI级别,返回的状态码便只能是“200”或其他如“302”之类的重定向状态码了。

其次,在自定义网站的404错误页面时,对设置的错误页面URL链接应使用相对路径而不是绝对路径,而且自定义404页面应该放在网站根目录下。尽管无 效链接可能是多种形式的URL,但当发生404访问错误时,WEB服务器会自动将其转到自定义的当404错误页中,这跟URL的形似没有关系。

(二)Apache下设置404错误页面

为Apache Server设置 404错误页面的方法很简单,只需在.htaccess 文件中加入如下内容即可:
ErrorDocument 404 /notfound.php

注意:
1.切记不要将404错误转向到网站主页,否则可能会导致主页在搜索引擎中消失
2.切记不要使用绝对URL(例如:http://www.bloghuman.com/nofound.php形式),如果使用绝对URL返回的状态码是“302”+“200”(已测试)

(三)IIS/ASP.net下设置404错误页面

首先,修改应用程序根目录的设置,打开 “web.config” 文件编辑,在其中加入如下内容:

<configuration>
<system.web>
<customErrors mode=”On” defaultRedirect=”error.asp”>
<error statusCode=”404″ redirect=”notfound.asp” />
</customErrors>
</system.web>
</configuration>

注:上文例中“error.asp”为系统默认的404页面,“notfound.asp”为自定义的404页面,使用时请修改相应文件名。

然后,在自定义的404页面“notfound.asp”中加入:

<%
Response.Status = “404 Not Found”
%>

这样,便可以保证IIS能够正确地返回“404”状态码

(四)在IIS/ASP.net下设置404静态页面

设 置静态404错误页面的方法则比较简单,在IIS管理器中右键单击要管理的网站,打开“属性”中的“自定义错误信息”页,为“404”设定相应的错误信息 页即可。不过,此处在“消息类型”中一定要选择“文件”或“默认值”,而不要选择“URL”,不然,将导致返回“200”状态码。

apache常见错误解决方案

转自: http://www.devgg.com/?p=210

多个站点的定义如下

#NameVirtualHost *:80

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for requests without a known
# server name.
#
NameVirtualHost 127.0.0.1:80

<VirtualHost 127.0.0.1:80>
ServerAdmin devgg@devgg.com
DocumentRoot /usr/local/tomcat/webapps/ronglian
ServerName www.ronglian.com
ErrorLog logs/ronglian.com-error_log
CustomLog logs/ronglian.com-access_log common
</VirtualHost>

<VirtualHost 127.0.0.1:80>
ServerAdmin devgg@devgg.com
DocumentRoot /usr/local/wwwroot/chinaface
ServerName www.chinaface.net
ErrorLog logs/chinaface.net-error_log
CustomLog logs/chinaface.net-access_log common
</VirtualHost>

在这里,NameVirtualHost的字段不能省略,否则起apache时报错:

VirtualHost 127.0.0.1.80 overlaps with VirtualHost 127.0.0.1:80, the first has precedence, perhaps you need a NameVirtualHost directive——虽然apache能起,
同错误描述一样,第二个站点的定义被第一个站点的定义所覆盖,即访问第二个站点指向的其实是第一个

NameVirtualHost 字段的端口号不能忽略,否则起apache时报错:
VirtualHost 127.0.0.1:80 — mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results
[error] VirtualHost 127.0.0.1:80 — mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results——apache不能起

如果VirtualHost 字段的端口号确实可用,起apache时报错:
VirtualHost 220.231.32.28:0 — mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results——
但apache可以启动,访问也正常

3 Could not reliably determine the server’s fully qualified domain name

加入ServerName 127.0.0.1即可。

Apache的rewrite的重写相关的参数

Apache mod_rewrite规则重写的标志一览

R[=code](force redirect) 强制外部重定向
强制在替代字符串加上http://thishost[:thisport]/前缀重定向到外部的URL.如果code不指定,将用缺省的302 HTTP状态码。
F(force URL to be forbidden)禁用URL,返回403HTTP状态码。
G(force URL to be gone) 强制URL为GONE,返回410HTTP状态码。
P(force proxy) 强制使用代理转发。
L(last rule) 表明当前规则是最后一条规则,停止分析以后规则的重写。
N(next round) 重新从第一条规则开始运行重写过程。
C(chained with next rule) 与下一条规则关联
如果规则匹配则正常处理,该标志无效,如果不匹配,那么下面所有关联的规则都跳过。
T=MIME-type(force MIME type) 强制MIME类型
NS (used only if no internal sub-request) 只用于不是内部子请求
NC(no case) 不区分大小写
QSA(query string append) 追加请求字符串
NE(no URI escaping of output) 不在输出转义特殊字符
例如:RewriteRule /foo/(.*) /bar?arg=P1%3d$1 [R,NE] 将能正确的将/foo/zoo转换成/bar?arg=P1=zed
PT(pass through to next handler) 传递给下一个处理
例如:
RewriteRule ^/abc(.*) /def$1 [PT] # 将会交给/def规则处理
Alias /def /ghi
S=num(skip next rule(s)) 跳过num条规则
E=VAR:VAL(set environment variable) 设置环境变量

使用mod_rewrite时常用的服务器变量:
HTTP headers:HTTP_USER_AGENT, HTTP_REFERER, HTTP_COOKIE, HTTP_HOST, HTTP_ACCEPT
connection & request: REMOTE_ADDR, QUERY_STRING
server internals: DOCUMENT_ROOT, SERVER_PORT, SERVER_PROTOCOL
system stuff: TIME_YEAR, TIME_MON, TIME_DAY

RewriteRule规则表达式的说明:
    . 匹配任何单字符
    [chars] 匹配字符串:chars
    [^chars] 不匹配字符串:chars
    text1|text2 可选择的字符串:text1或text2
    ? 匹配0到1个字符
    * 匹配0到多个字符
    + 匹配1到多个字符
    ^ 字符串开始标志
    $ 字符串结束标志
    n 转义符标志

反向引用 $N 用于 RewriteRule 中匹配的变量调用(0 <= N <= 9)
反向引用 %N 用于 RewriteCond 中最后一个匹配的变量调用(1 <= N <= 9)

RewriteCond适用的标志符
‘nocase|NC’ (no case)忽略大小
‘ornext|OR’ (or next condition)逻辑或,可以同时匹配多个RewriteCond条件

RewriteRule适用的标志符
‘redirect|R [=code]’ (force redirect)强迫重写为基于http开头的外部转向(注意URL的变化) 如:[R=301,L]
‘forbidden|F’ (force URL to be forbidden)重写为禁止访问
‘proxy|P’ (force proxy)重写为通过代理访问的http路径
‘last|L’ (last rule)最后的重写规则标志,如果匹配,不再执行以后的规则
‘next|N’ (next round)循环同一个规则,直到不能满足匹配
‘chain|C’ (chained with next rule)如果匹配该规则,则继续下面的有Chain标志的规则。
‘type|T=MIME-type’ (force MIME type)指定MIME类型
‘nosubreq|NS’ (used only if no internal sub-request)如果是内部子请求则跳过
‘nocase|NC’ (no case)忽略大小
‘qsappend|QSA’ (query string append)附加查询字符串
‘noescape|NE’ (no URI escaping of output)禁止URL中的字符自动转义成%[0-9]+的形式。
‘passthrough|PT’ (pass through to next handler)将重写结果运用于mod_alias
’skip|S=num’ (skip next rule(s))跳过下面几个规则
‘env|E=VAR:VAL’ (set environment variable)添加环境变量

实战
    例子:
    RewriteEngine on
    RewriteCond %{HTTP_USER_AGENT} ^MSIE [NC,OR]
    RewriteCond %{HTTP_USER_AGENT} ^Opera [NC]
    RewriteRule ^.* – [F,L] 这里”-”表示没有替换,浏览器为IE和Opera的访客将被禁止访问。

    例子:
    RewriteEngine On
    RewriteBase /test
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule ([^/]+)$ /test/$1.php
    #for example: /test/admin => /test/admin.php
    RewriteRule ([^/]+).html$ /test/$1.php [L]
    #for example: /test/admin.html => /test/admin.php

    限制目录只能显示图片
    < IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteCond %{REQUEST_FILENAME} !^.*.(gif|jpg|jpeg|png|swf)$
    RewriteRule .*$ – [F,L]
    < /IfModule>

转: Linux下Apache基本配置指南

1、如果找不到文件的具体位置,在Linux下可以用类似locate httpd.conf的指令来搜索文件的位置。如果搜索不到,可以先用updatedb指令更新索引数据库再用locate搜索。

2、apachectl configtest或apachectl –t检查配置文件是否合法。apachectl一般位于安装目录的bin目录下(如:/usr/local/apache2/bin)。不要直接调用httpd。

3、配置文件是httpd.conf;在Linux系统中,它可能存在于系统配置目录(如:/etc/httpd/conf/),也可能存在于Apache的安装目录(如:/usr/local/apache2/conf)。

4、配置文件中,一行包含一个指令,但行尾可以用表示续行。与下一行之间不能有其它任何字符,包括空白字符。
#表示这一行是注释。

5、指令对大小写不敏感,但是参数对大小定敏感,在Linux系统下,路径也要注意大小写。路径后不必加/。

6、类似于<Directory></Directory>表示一个配置段。大多数配置段中的指令仅针对配置段所匹配的请求有 效。但诸如        <IfDefine>、<IfModule>、<IfVersion>之类,是在Apache启动时,如果条 件成立才有效,并且对所有请求都有效。

httpd.conf的基本配置选项

7、ServerName服务器名称。它用来创建URL的重导向。ServerName是apache服务器自身识别访问请求的标记之一,他不必与实际IP或DNS名称一致。也可以不设置,如果这样,那apache会试图用IP来作为请求的标记。端口也可以不设置。
例:ServerName www.example.com:80

8、ServerAdmin管理员的电子邮件地址。服务器的错误提示页会用到。如果ServerSignature定义为Email的话,将在错误页的页尾增加ServerAdmin的链接。

9、Listen服务器监听的地址和端口。端口一定要指定。默认情况下,服务器会监听本机的所有地址。可以同时使用多个Listen指令。
例一:同时所有接受来自端口80和8000的请求
Listen 80
Listen 8080
例二:指定地址+端口,配置虚拟主机时,会需要这样设置。详细看虚拟主机的设置。这并不是必要的。
Listen 192.168.0.2:80
Listen 192.168.0.1:8080
注意地址是本机的地址,是指客户端对本机某个地址的请求。地址可以是域名,但最好是IP地址。
例三:IPv6地址必须用方括号括起来。
Listen [2001:db8::a00:20ff:fea7:ccea]:80
例四:要使Apache只处理IPv4的请求,只需如此:
Listen 0.0.0.0:80

10、ServerRoot 服务器基础目录,一般就是Apache的安装目录,不必更改。

11、DocumentRoot 指定主目录。不指定的话,默认目录一般是ServerRoot目录下的htdocs目录(如/usr/local/apache2/htdocs),视版 本而定;但是可能会有例外,所以最好指定。如果指定相对路径,则认为是相对于ServerRoot目录的。目录后不要加/。

12、DirectoryIndex 默认首页名称。多个默认页名称用空格隔开。

13、ErrorDocument 处理请求出错时的处理方式。未配置时只返回错误代码。
例:
ErrorDocument 500 "The server made a boo boo."
# 指定本地URL时,该URL是相对于DocumentRoot目录的。
ErrorDocument 404 /missing.html
ErrorDocument 404 "/cgi-bin/missing_handler.pl"
# 使用绝对URL时,客户机将无法收到错误码。
ErrorDocument 402 http://www.example.com/subscription_info.html

14、ErrorLog,CustomLog 指定错误日志和访问日志。如果指定路径是相对路径,则认为是相对ServerRoot目录的。日志文件可能会很大,以至影响到其它文件的储存空间,所以有必要把日志文件放到一个单独的分区。
例一:
ErrorLog /var/log/error_log
# commom是日记文件的格式,由LogFormat定义。不可用于ErrorLog。
Customlog /var/log/access_log common
例二:管道日志,可以用Apache提供的rotatelogs来实现。rotatelogs程序一般位于安装目录的bin目录。
# 这将每24小时建立日志文件/var/log/logfile.nnnn,nnnn是日记建立时的系统时间。
CustomLog “|bin/rotatelogs /var/log/logfile 86400”common
# 日志文件达到5M时建立新日记,文件名类似于logfile.2006-12-30-24_33_12。
ErrorLog “|bin/rotatelogs /var/log/logfile.%Y-%m-%d-%H_%M_%S 5M”

15、User, Group 指定运行服务子进程的用户和组。Rpm包安装apache时会自动设置一个用户和组,但有时会设成nobody或者不设置。为了安全和方便管理,设置为用户和组为apache是很重要的。
例:User apache
Group apache
注意在Linux系统中手动添加apache用户和组时,必须把他们的shell指定为nologin

虚拟主机

16、虚拟主机通过<VirtualHost>配置段来配置,配置段里的指令对虚拟主机有效,配置段没有配置的,将采用全局的配置。检查虚拟主机的配置可用apachectl –S(可能某些版本这个参数无效)。

17、基于域名的虚拟主机在DNS把多个域名都映射到同一IP的情况下有用。典型的配置如下:
NameVirtualHost *:80
<VirtualHost *:80>
ServerAdmin webmaster@test.com
DocumentRoot /www/docs/test.com
ServerName test.com
ErrorLog logs/dummy-host.example.com-error_log
CustomLog logs/dummy-host.example.com-access_log common
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /www/docs/test2.com
ServerName test2.com
</VirtualHost>

NameVirtualHost *:81
<VirtualHost *:81>
DocumentRoot /www/docs/test3.com
ServerName test3.com
</VirtualHost>
注意一:NameVirtualHost 指定虚拟主机所使用的IP地址或域名,但是最好是IP地址。使用基于域名的虚拟主机时,NameVirtualHost是必要的指令。NameVirtualHost可以定义多个。
注意二:所有符合NameVirtualHost或<VirtualHost>标签定义的请求,都会被作为虚拟主机处理,而主服务器将不理 会。NameVirtualHost定义了而<VirtualHost>标签没有定义的的请求,服务器会找不到相应的虚拟主机而将无法处理。 所以每个NameVirtualHost定义的参数至少要有一个<VirtualHost>相匹配。
注意三:如果设置NameVirtualHost 或<VirtualHost>为*:80的话,所有针对80端口的请求,都会被虚拟主机处理,请求会根据域名指向某个虚拟主机。如果有来自 80端口的请求,而所请求的域名没有被配置为虚拟主机,那将指向第一个虚拟主机。这样主服务器将无法收到来自80端口的任何请求。为此也要为主服务器配置 一个虚拟主机。

18、ServerAlias 虚拟主机的别名
例:
NameVirtualHost *:80
<VirtualHost *:80>
       ServerName www.domain.tld
       ServerAlias domain.tld *.domain.tld
       DocumentRoot /www/domain
</VirtualHost>
这表示对 domain.tld和*.domain.tld的请求也由虚拟主机www.domain.tld处理。

19、ServerPath指令是用于让某些老式浏览器也访问基于域名的虚拟主机的,一般不必设置。

20、基于IP地址的虚拟主机。例:
Listen 80
<VirtualHost 172.20.30.40>
DocumentRoot /www/example1
ServerName www.example.com
</VirtualHost>
<VirtualHost 172.20.30.50 192.168.0.10:80>
DocumentRoot /www/example2
ServerName www.example.org
</VirtualHost>
每个虚拟主机可定义多个IP,之间用空格隔开。

21、各种虚拟主机的混用。例:
Listen 80
Listen 81

NameVirtualHost 172.20.30.40
<VirtualHost 172.20.30.40>
DocumentRoot /www/example1
ServerName www.example.com
</VirtualHost>
<VirtualHost 172.20.30.40>
DocumentRoot /www/example2
ServerName www.example.org
</VirtualHost>

NameVirtualHost 172.20.30.40:81
<VirtualHost 172.20.30.40:81>
DocumentRoot /www/example3
ServerName www.example3.net
</VirtualHost>

# IP-based
<VirtualHost 172.20.30.50>
DocumentRoot /www/example4
ServerName www.example4.edu
</VirtualHost>
<VirtualHost 172.20.30.60:81 172.20.30.40:81>
DocumentRoot /www/example5
ServerName www.example5.gov
</VirtualHost>

22、虚拟主机混用时的问题:
一、虚拟主机混用可以这样理解:一行NameVirtualHost指令定义的所有虚拟主机为一组;该组与一个基于IP的虚拟主机平级。即把一行NameVirtualHost定义的整个组看作是一个基于IP的虚拟主机。
二、虚拟主机指定的端口必须是Listen定义的。如果虚拟主机没有指定端口,则认为是80端口。如果NameVirtualHost * 这样定义,是指所有地址的所有已定义端口。
三、更具体的地址定义优先。比如NameVirtualHost指令定义了*:80,而某个基于IP的虚拟主机定义为192.168.0.1:80,那么 此时如有对192.168.0.1:80的请求,那请求会被优先指向192.168.0.1:80定义的虚拟主机。所以为了避免混乱,不要定义相互有交叉 或包含的地址区间。
四、一个虚拟主机,可以同时为基于域名和基于IP的。如上一例中最后一个虚拟主机。这样符合两种定义的请求都会被指同一个虚拟主机。有时要区别内外网对虚拟主机的访问时可以这样,因为来自内网的请求可能和来自外网的请求可能不一样,但是它们需要指向同一个虚拟主机。

23、使用"_default_"虚拟主机,这个虚拟主机可以理解成基于IP的虚拟主机。例:
<VirtualHost _default_:*>
DocumentRoot /www/default
</VirtualHost>
这个虚拟主机将接管与其它虚拟主机IP和端口不匹配的请求。不过如此一来,主服务器将不会处理任何请求。因此把主服务器配置成一个虚拟主机是必要的。

24、本地机器代理在其它机器上运行的虚拟主机。例:
<VirtualHost 158.29.33.248>
ProxyPreserveHost On
ProxyPass /foo/no !
ProxyPass /foo http://192.168.111.2
ProxyPassReverse /foo http://192.168.111.2
ServerName hostname.example.com
</VirtualHost>
一、首先这是一个基于IP的虚拟主机,它接收并处理对IP地址158.29.33.248的请求。
二、ProxyPass /foo http://192.168.111.2 将把对http://158.29.33.248/foo的请求转换为一个代理请求,该请求指向http://192.168.111.2
三、ProxyPass /foo/no ! 不代理针对/foo/no的请求。这个必须放在正常代理指令之前。
四、ProxyPreserveHost On 意思是传送原始请求的Host信息给被代理的机器。
五、ProxyPassReverse /foo http://192.168.111.2 可以保证请求URL在其它机器上被重定向后,本机处理时也可以保持一致。具体看手册关于反向代理的部分。
六、基于域名的虚拟主机也是同样的道理。不管是什么类型的虚拟主机,它只是处理归它处理的请求而已。

配置段

25、<IfDefine> 只有在用httpd命令行启动服务器时(最好不要直接使用httpd,用apachectl代替),使用了-D参数定义了相应参数时才生效。如服务器用 apachectl –D test启动时,<IfDefine test>配置段生效。

26、<IfVersion> 例如:<IfVersion >= 2.0.55> 当Apache版本不低于2.0.55时生效。

27、<IfModule> 服务器启用了指定的模块后才生效。这是最常用的。例如<IfModule mod_mine_magic.c>。

28、<Directory> 用于封装一组指令,使之对某个目录和下属的子目录有效。
例:
<Directory />
       Options FollowSymLinks Indexes
       AllowOverride None
       Order Deny,Allow
       Deny from All
       Allow from example.com
</Directory>
该配置段对整个根目录树有效。
一、Options 常用选项:FollowSymlinks允许在此目录中使用符号链接;Indexes允许目录列表,即在该目录没有默认页时服务器返回该目录的列表给客户 机;SymLinksIfOwnerMatch只有符号链接与其目的目录或文件属于同一用户时才有效。
注意:对同一目录,只有一行Options有效,如果定义某个目录的Options同时要继承上级目录的定义,可以这样:Options +Indexes。如果这样:Options +Indexes –FollowSymLinks,这将为本级目录增加Indexes,取消FollowSymLinks。
二、AllowOverride 常用选项:None 不允许使用.htaccess;All允许在.htaccess中使用所有的指令。一般不必使用.htaccess,而且为了安全和效率起见,设置为None比较好。
三、Order 访问控制,控制条件由Deny行和Allow行定义。Order指令常用选项:Deny,Allow 除了符合条件的外,其它的也允许访问;Allow,Deny 除了符合条件的外,其它的不允许访问。
Deny from All是拒绝所有的访问,Allow from example.com是允许example.com域访问该目录(意思是如果该服务器上有多个虚拟主机的话,只有example.com可以访问该目 录)。三行合起来的意思就是只允许example.com域访问根目录。当然这只是个例子,应该禁止所有域对根目录的访问。注意:Deny,Allow指 令生效的顺序取决于Order中Deny和Allow的顺序。
注意<Directory>不能嵌套。
这样为了安全起见常常需要设置:
#拒绝对所有目录的访问,注意这里的/是指操作系统的根目录,而非DocumentRoot目录。
<Directory />
       Options –Indexes -FollowSymLinks
       AllowOverride None
       Order Allow,Deny
</Directory>
#允许所有对/var/htdocs的访问,允许对/var/htdocs的文件列表。
<Directory /var/htdocs>
       Options +Indexes
       Order Deny,Allow
</Directory>

29、<Files>和<Directory>类似,不过它定义的是对文件的访问控制。它们都可以接受正则表达式为参数,格式 如<Files ~ ".(gif|jpe?g|png)$">或者<FilesMatch ".(gif|jpe?g|png)$">。

30、<Location>与<Files>和<Directory>同,不过它定义的是对URL的访问控制。

PHP配置

31、加载php模块:LoadModule php5_module modules/libphp5.so

32、AddModule mod_php5.c (不是必须的)

33、哪种后缀的文件作为php脚本来解析:AddType application/x-httpd-php .php (这是必须的,但是可以用下面的配置代替):
<Files *.php>
SetOutputFilter PHP
SetInputFilter PHP
</Files>
这种方法还可以为.php文件专门设置更多的配置。

34、哪种后缀的文件是php源文件:Addtype application/x-httpd-php-source .phps (不是必须的)

35、添加index.php为目录首页:DirectoryIndex index.php(视情况而定)

36、ScriptAlias /php/ /usr/local/php/ 对类似http://example/php/abc.php的请求将引导执行/usr/local/php/abc.php脚本。 (一些所谓配置指南里有,事实上完全没有这个必要。并且ScriptAlias这个指令是针对CGI脚本的。他会把php脚本也当作已定义的cgi脚本处理)。

37、Action application/x-httpd-php "C:/PHP/php.exe" 所有application/x-httpd-php类型的文件都由C:/PHP/php.exe来处理,注意application/x-httpd- php必须是已经定义的文件类型。 (只有在windows中以CGI模式安装PHP时才有用)。

38、事实上,必要的配置只有这么两条:
LoadModule php5_module modules/libphp5.so
AddType application/x-httpd-php .php
可以把相关php的配置语句都放在一起便于管理。简单至此,不要被一些配置指南吓住了。

Virtual Hosting using Apache 2 on a linux machine

Virtual Hosting allow web servers to host more than one website on a sing machine. This is how sharing hosting works. I become pretty handy as well while develloping different web project on the same machine and allows you to access to your local repository using addresses such as http://dev.mysite.com instead of http://localhost/~myuser/myproject/ :) .
This tutorial is based on a machine runnning ubuntu/linux but should be the same on any debian based distribution and almost the same on other distributions.

First of all, you need an apache server ready to run on your machine, if it is not yet install, open a terminal and type

$sudo apt-get install apache2-utils apache2-common

Once the server is installed, it is time to get into apache 2 configuration.
Let’s open apache’s main configuration file, name /etc/apache2/apache2.conf. A search for the word virtual bring us to the following line:

Include /etc/apache2/sites-enabled/[^.#]*

This mean that when starting apache, it will look for files in /etc/apache2/sites-enabled/.
Lets go there and see what is in.

$cd /etc/apache2/sites-enabled/

$ls -l

total 1

lrwxrwxrwx 1 root root 36 2005-12-27 01:42 000-default -> /etc/apache2/sites-available/default

Well, this only links to the file in directory /etc/apache2/sites-available/ . You might wonder what is the point in doing such. Well, this simply allows you, mainly when you are using your box as a web server, to:

  1. Have a simple main configuration file
  2. Do be able to edit or create a new host by creating/editing a file from /etc/apache2/sites-available/
  3. In case your web server doesn’t restart because of misconfiguration, you can simply remove the link from the file in /etc/apache2/sites-enabled/ pointing to the malformed file in /etc/apache2/sites-available/

Now let say you want to be able to map the domain name dev.example.com to you local machine, using the code file in /home/myuser/public_html/example.com/.
While in /etc/apache2/sites-available, create a new file (let say example.com.conf)

$sudo vi example.com.conf

Now add the following lines:

<VirtualHost dev.example.com>
ServerAdmin webmaster@localhost
#We want to be able to access the web site using www.dev.example.com or dev.example.com
ServerAlias www.dev.example.com
DocumentRoot /home/myuser/public_html/example.com
#if using awstats
ScriptAlias /awstats/ /usr/lib/cgi-bin/
#we want specific log file for this server
CustomLog /var/log/apache2/example.com-access.log combined
</VirtualHost>

Note:People who don’t want to bother knowing how the site enabling system works might just jump to the end of the article to find debian built-in command syntax. If you want to know how it works, or do not use a debian based distro, carry on.

Now, we specified a new host to apache but it is not yet linked to the repertory where apache actually look for virtual hosts. Let go to:

$cd /etc/apache2/sites-enabled/

and create a link to the file we just created:

$sudo ln -s /etc/apache2/sites-available/example.com.conf example.com.conf

Now apache is almost ready to restart, but before doing so, we must inform our linux system that dev.example.com and www.dev.example.com are not to be looked for on the net, but on the local machine instead.
To do so, simply edit /etc/hosts and add the new host names at the end of the line beginning by 127.0.0.1, which is localhost.
In the end, your file should look like:

127.0.0.1 localhost.localdomain localhost dev.example.com www.dev.example.com

And now we are done, simply reload apache:

sudo /etc/init.d/apache2 reload

Open your web browser and enter the following address dev.example.com. Magic, it runs the same as when you were using http://localhost/~myuser/example.com but it is far more usefull when devellopping a web service and want to be able to develop applications on your machine just like it is where the real web site.

Edit: As you can see from the comments, many people pointed out that you can use a debian specific command (so if you are not using a debian based system, don’t expect to find that command :) ).
to enable a new virtual host simply type:

sudo a2ensite mysiteavailable-site

to disable a virtual host:

sudo a2dissite mysiteavailable-site

where mysiteavailable-site is the name of the virtual hos you want to enable/disable, so in out example: example.com.conf

返回顶部