Skip navigation.

极湖

无不用其“极”

Posts tagged with "Apache"

通过 Subversion 的 hook 自动更新代码

,

用 subversion (以下简称 svn) 做版本管理,可以免去 ftp 上传代码的过程,具体方法是通过 svn 的 commit hook 自动更新代码。

以下是设置的步骤:

切换到 root 用户。
# su -

导出项目。
# cd /home
# svn checkout --username USER_NAME --password USER_PASS http://localhost/svn/PROJECT_NAME/trunk/ PROJECT_NAME
# chown -R USER_NAME PROJECT_NAME


编写 shell 脚本。
# vi /home/USER_NAME/bin/svn_auto_update.sh
输入
#!/bin/sh
date >> /tmp/svn_auto_update
cd /home/PROJECT_NAME
echo "$1 --- $2" >> /tmp/svn_auto_update  2>&1
svn status | awk '/^?/ {print $2}'  | xargs rm -Rvf >> /tmp/svn_auto_update 2>&1
svn update --username USER_NAME --password USER_PASS >> /tmp/svn_auto_update 2>&1

更改脚本的所有者。
# chown -R USER_NAME PROJECT_NAME /home/USER_NAME/bin/svn_auto_update.sh

设置 svn 的 hook。
# cd /home/svnrepo/PROJECT_NAME/hooks
# cp post-commit.tmpl post-commit
# chmod a+x post-commit
# vi post-commit

追加
date >> /tmp/svn_log
/usr/bin/sudo -H -u USER_NAME /home/USER_NAME/bin/svn_auto_update.sh $REPOS $REV >> /tmp/svn_log &


把 apache 用户加入 sudoer。
# usermod -G apache USER_NAME
# visudo

追加
apache  ALL=(USER_NAME) NOPASSWD: /home/USER_NAME/bin/svn_auto_update.sh


说明:

1.以上命令和代码中的 USER_NAME 是用户名,USER_PASS 使用户密码,PROJECT_NAME 是项目名,不同环境会有不同的名字。

2.以上设置,前提是 apache 和 subversion 在同一台机器上,svn 项目已经建立,apache 的 svn 设置也已经做好。

用 Apache Bench 进行网站性能测试

, , , ...

Apache 有一个自带的性能测试工具叫 ab (Apache Bench)。
用这个工具,只须指定同时连接数、请求数以及URL,即可测试网站或网站程序的性能。

通过 ab 命令发送请求之后,可以得到每秒传送字节数、每秒处理请求数、每请求处理时间等统计数据。

举个例子,要得到同时连接数为 100、请求数达 1000,访问 http://example.com/index.html 的性能测试数据,命令格式如下:
ab -n 1000 -c 100 http://example.com/index.html

若目标地址需用户认证,可加 -A 参数。

ab 命令的常用参数:
-n 数值: 发起测试的请求数
-c 数值: 发起测试的同时连接数
-A 用户名:密码

需要注意的是,ab 只是对单一文件的请求,访问对象带有图像文件等情况下,则要具体情况具体分析。

下面是 ab 命令具体运用的一个实例:

# ab -n 1000 -c 10 http://localhost/foo/cache/
This is ApacheBench, Version 2.0.40-dev <$Revision: 1.121.2.1 $> 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 localhost (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.46
Server Hostname: localhost
Server Port: 80

Document Path: /foo/cache/
Document Length: 26 bytes

Concurrency Level: 10
Time taken for tests: 11.986245 seconds
Complete requests: 1000
Failed requests: 0
Write errors: 0
Total transferred: 223000 bytes
HTML transferred: 26000 bytes
Requests per second: 83.43 [#/sec] (mean)
Time per request: 119.862 [ms] (mean)
Time per request: 11.986 [ms] (mean, across all concurrent requests)
Transfer rate: 18.10 [Kbytes/sec] received

Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.8 0 26
Processing: 11 114 408.0 92 7412
Waiting: 0 74 317.4 34 4143
Total: 11 115 408.0 92 7412

Percentage of the requests served within a certain time (ms)
50% 92
66% 104
75% 104
80% 104
90% 106
95% 132
98% 332
99% 983
100% 7412 (longest request)

xCache 的安装及使用

, , ,

1. 安装
$ wget http://xcache.lighttpd.net/pub/Releases/1.2.2/xcache-1.2.2.tar.gz
$ tar -zxvf xcache-1.2.2.tar.gz
$ cd xcache-1.2.2
$ phpize
$ ./configure --enable-xcache --with-php-config=/usr/local/bin/php-config
$ make
$ make test
$ make install


2. PHP 的 ini 设置
$ cd /usr/local/lib
$ cp php.ini php.ini.bak
$ vi php.ini

追加
[xcache-common]
zend_extension = "/usr/local/lib/php/extensions/no-debug-non-zts-20060613/xcache.so"

[xcache.admin]
xcache.admin.auth = On
xcache.admin.user = "mOo"
; xcache.admin.pass = md5($your_password)
xcache.admin.pass = ""

[xcache]
xcache.shm_scheme = "mmap"
xcache.size = 40M
xcache.count = 1
xcache.slots = 8K
xcache.ttl = 0
xcache.gc_interval = 0
xcache.var_size = 1M
xcache.var_count = 1
xcache.var_slots = 8K
xcache.var_ttl = 0
xcache.var_maxttl = 0
xcache.var_gc_interval = 300
xcache.test = Off
xcache.readonly_protection = Off
xcache.mmap_path = "/tmp/xcache"
xcache.coredump_directory = ""
xcache.cacher = On
xcache.stat = On
xcache.optimizer = Off

[xcache.coverager]
xcache.coverager = Off
xcache.coveragedump_directory = "/tmp/pcov"

各参数的具体意思,请参阅 xCache 的文档

确认安装成功
$ php -v
PHP 5.2.5 (cli) (built: Nov 13 2007 15:19:18)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
with XCache v1.2.2, Copyright (c) 2005-2007, by mOo

3. 重启 Apache
$ /etc/init.d/httpd restart

4. PHP程序缓存处理
实例:
<?php
if(!xcache_isset("test")) {
    xcache_set("test", strftime('%Y-%m-%d %A %H:%M:%S', time()), 30);
}
echo xcache_get("test");
?>

eAccelerator 的安装及使用

, , ,

1. 安装
$ wget http://nchc.dl.sourceforge.net/sourceforge/eaccelerator/eaccelerator-0.9.5.2.tar.bz2
$ tar -jxvf eaccelerator-0.9.5.2.tar.bz2
$ cd eaccelerator-0.9.5.2
$ phpize
$ ./configure --enable-eaccelerator=shared --with-php-config=/usr/local/bin/php-config
$ make
$ make test
$ make install


若有必要,先安装 re2c:
$ wget http://nchc.dl.sourceforge.net/sourceforge/re2c/re2c-0.12.3.tar.gz
$ tar xzvf re2c-0.12.3.tar.gz
$ cd re2c-0.12.3
$ ./configure
$ make
$ make install


2. PHP 的 ini 设置
$ cd /usr/local/lib
$ cp php.ini php.ini.bak
$ vi php.ini

追加
[eaccelerator]
zend_extension="/usr/local/lib/php/extensions/no-debug-non-zts-20060613/eaccelerator.so"
eaccelerator.shm_size = "32"
eaccelerator.cache_dir = "/var/cache/eaccelerator"
eaccelerator.enable = "1"
eaccelerator.optimizer = "1"
eaccelerator.check_mtime = "1"
eaccelerator.debug = "0"
eaccelerator.filter = ""
eaccelerator.shm_max = "0"
eaccelerator.shm_ttl = "0"
eaccelerator.shm_prune_period = "0"
eaccelerator.shm_only = "0"
eaccelerator.compress = "1"
eaccelerator.compress_level = "9"
eaccelerator.keys     = "shm_and_disk"
eaccelerator.sessions = "shm_and_disk"
eaccelerator.content  = "shm_and_disk"

具体设置,请参阅 eAccelerator 的文档

不要忘了建立缓存目录
$ mkdir -p /var/cache/eaccelerator
$ chmod a+w /var/cache/eaccelerator


确认安装成功
$ php -v
PHP 5.2.5 (cli) (built: Nov 13 2007 15:19:18)
Copyright (c) 1997-2007 The PHP Group
Zend Engine v2.2.0, Copyright (c) 1998-2007 Zend Technologies
with eAccelerator v0.9.5.2, Copyright (c) 2004-2006 eAccelerator, by eAccelerator

3. Apache设置
有VirtualHost的情况下,推荐设置如下
NameVirtualHost *:80
<VirtualHost *:80>
    ServerName vhost1
......
    php_admin_value eaccelerator.name_space "vhost1"
</VirtualHost>

<VirtualHost *:80>
    ServerName vhost2
......
    php_admin_value eaccelerator.name_space "vhost2"
</VirtualHost>


重启Apache
$ /etc/init.d/httpd restart

4. PHP程序缓存处理
推荐: PHP Caching object for XCache or eAccelerator
*注意: 最新版的 eAccelerator 默认禁用 shm 函数。

实现域名重定向的 Rewrite 写法

, ,

一. http(默认 80 端口)
RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain2.com
RewriteRule ^(.*)$ http://domain1.com/$1 [R,L]


二. https(默认 443 端口)
写法一:
RewriteCond %{HTTP_HOST} ^domain2.com
RewriteCond %{HTTPS} ^on$
RewriteRule ^(.*)$ https://domain1.com/$1 [R,L]


写法二:
RewriteCond %{HTTP_HOST} ^domain2.com
RewriteCond %{SERVER_PORT} ^443$
RewriteRule ^(.*)$ https://domain1.com/$1 [R,L]


三. http + https(所有端口)
RewriteCond %{HTTP_HOST}   ^domain2.com
RewriteCond %{SERVER_PORT} !^80$
RewriteRule ^(.*)$         http://domain1.com:%{SERVER_PORT}/$1 [L,R]
RewriteCond %{HTTP_HOST}   ^domain2.com
RewriteRule ^(.*)$         http://domain1.com/$1 [L,R]

Apache: 重定向到另一个域名的设置

,

在httpd.conf或相关设置文件中作如下设置即可实现:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.domain1.com
RewriteRule ^(.*)$ http://www.domain2.com/$1 [R=permanent]

解决一个Apache启动过程中的错误

,

因为apache用到了mod_auth_pgsql模块,启动时候出错误:

错误信息:
# /etc/init.d/httpd start
httpdを起動中: Syntax error on line 211 of /usr/local/apache2/conf/httpd.conf:
Cannot load /usr/local/apache2/modules/mod_auth_pgsql.so into server: libpq.so.4: cannot open shared object file: No such file or directory
                                                           [失敗]

解决办法:
# vi /etc/ld.so.conf  
(追加)
/usr/local/pgsql/lib/

# ldconfig

之后重新启动apache,OK。

Apache 调优招数 (译文)

,

前不久转贴了一篇题为“Apache 调优招数”的英文文章,文中说是“有时间真该翻译”,然而因为太懒,还有就是忙着别的事,所以一直没有翻译。惭愧!

今天,意外收到一封署名“Bai Shi”的邮件,,他把翻译好的文章给我发了过来。真是非常感谢这位热心的同行!我把他翻译的文章转贴在此,相信大家和我一样会从中受益。

Apache 微调小贴士:

  1. 升级 Apache!最新版的 Apache 总会有系统性能的优化。

  2. 修改 httpd.conf,设置“HostNameLookups off”,阻止 Apache 对每一个访问记录进行反向DNS查询。

  3. 如果你的站点很繁忙,修改 httpd.conf,设置“MaxClients 230”或者更大,这样可以同步运行更多的 httpd 守护进程,防止进程队列阻塞。[不过过度增加以至于耗尽你的剩余内存,通常每进程需要消耗2-8MB内存,这样230进程大约需要1G内存]

  4. 把图片如 GIF 文件等放在另外一台专用的服务器上。

  5. 确定你的网页和 CGI 程序允许利用客户端缓存。具体参见“Caching Tutorial for Web Authors and Webmasters”, 网址http://www.pobox.com/~mnot/cache_docs/ [或者: http://www.mnot.net/cache_docs/]。

  6. 保持你的 Apache 苗条整洁。只编译必需的模块。在编译前,修改 /apache_1.x.x/src/Configuration 文件,在所有不需要的 AddModule 行添加 # 来禁止该模块。

  7. 如果你不需要访问流量记录(比如专用的图像文件服务器),可以修改 httpd.conf 中的 TransferLog,将之重定向到 /dev/null。

  8. 除非你一定坚持要用 .htaccess 文件来控制目录权限(你有很多方法,’.htaccess 是其中一种不被推荐的’——译者)。修改 access.conf 或者在新版的 apache 中很可能是 httpd.conf,设置“AllowOverride None”使得 Apache 不必在每次受到请求时浪费时间搜索有关目录权限的文件。

  9. 不要在后台运行不必要的程序。禁用不必要的后台程序不仅可以很大的增强系统性能,而且能够提高系统安全性。/etc/rc.d/rc3.d/ 目录包含了系统自动启动的服务连接(这个目录在 Debian 中是 /etc/rc2.d/.-D.),删除不必要的服务的符号连接。通常一个专用的Web服务器仅仅需要 routed, network, inet, httpd 等。如果你修改了该目录,请重起使改动生效。

  10. 不要将网页文件和流量记录等文件放在网络文件系统上(例如 NFS 磁盘)——仅仅读写本地磁盘,因为 NFS 的输入输出操作会有很大的额外开销。

  11. 不要通过 /etc/inetd.conf 中的 tcpd wrapper 来启动 Apache。Apache 可以通过修改 rc.local 或 /etc/rc.d/rc3.d/ 目录来实现自动启用。如果需要阻止特定 IP 访问,可以在在 httpd.conf 中直接使用“deny from”来实现。

  12. 如果不用 Xwindow 系统,记得及时关掉。因为图形界面的系统开销很大——一个很简单的办法是通过 Ctrl-Alt-Backspace 来关掉X会话(在 Fedora Core 默认设置中无效,只会重新启动 Xwindow —— 译者)。

  13. 避免使用SSI标记。[http://www.squid-cache.org/mail-archive/squid-users/199901/0080.html SSI 页面可以通过修改 XbitHack full 设置恰当的 X-bit 来实现缓存。然而传统的应用 SSI 的做法很可能导致文档无法被缓存。

  14. CGI 脚本:
    o 文件输入输出:尽量少打开文件。确定每个被打开的文件都被恰当的关闭了。找到你所需的数据之后马上停止读取文件。考虑将数据文件结构化为定长字段,并使用 read() 函数来直接访问你所需的部分。
    o Shell 命令:在 Perl 脚本中,使用 Shell 命令的完整路径名而不是相对路径。
    o 如果你的站点以 CGI 脚本为主,尽量使用 mod_perl。
    o Perl程序员应该学习“Effective Perl Programming”,作者 Joseph N.Hall (出版社Addison Wesley)和“The Perl Cookbook”,作者 Tom Christiansen (出版社O’Reilly)——两本极好的 Perl 优化指南。例如:你可以预先分配一个256项的内存散列(哈西表 —— Hash table),通过如下命令: keys(%names) = 256。
    o 避免使用包含过多文件的目录。把你的网页文件组织进子目录中。在每次请求中,一个目录中文件越多,就有更多的时间浪费在文件定位上。

  15. 尽量少的使用图片,并确定每个图片都是通过图片压缩器输出的。

  16. 对网站进行压力测试,执行 Apache 测试程序(ab),程序通常在 /bin 或 /sbin(或/usr/local/bin或/usr/local/sbin —— 译者)。程序 ab 会模拟多线程大流量的访问请求来测算服务器负荷及响应时间,可以很有效的测量你的微调结果。

  17. 想要获得最好的性能,把网线从服务器上拔下来——你的负载几乎马上就会降到0。;-)

  18. 设置你 htdocs 所在的分区的 mount 选项“noatime”。

  19. 如果你有一个独立的分区来挂载 /tmp,你应该在 /dev/fstab 里面设置他的挂载选项为 nodev,noexec,nosuid。这样可以有效的防止黑客上传木马程序到 /tmp。

  20. 考虑使用 mod_gzip 压缩输出以减小流量(或 mod_deflate,如果你在使用 apache2),或者干脆把网页源文件给压缩了保存在磁盘上。

  21. 把 KeepAliveTimeout 改成大约2秒。这样使客户端有足够的时间通过一次连接完成所有内容的下载,避免生成新的进程来处理新的请求。

  22. 禁用 ExtendedStatus,除非你在进行系统调试。同样,慎用 mod_info。


译者:风子

用 .htaccess 设置 PHP 的参数

,

用Apache作Web服务器,PHP的选项除了用php.ini进行设置,还可以在目录下面建立.htaccess文件,对这个目录进行单独设置。
例:
DirectoryIndex index.html index.php
<IfModule mod_php4.c>
php_value mbstring.language japanese
php_value mbstring.internal_encoding SJIS
php_value include_path ".:/usr/local/lib/php:/home/myproject/src/include"
php_flag magic_quotes_gpc Off
php_flag magic_quotes_runtime Off
php_flag display_errors On
php_flag log_errors On
php_flag track_errors On
php_flag short_open_tag On
php_value error_log  /home/myproject/log/php_error.log
</IfModule>


前提是要打开AllowOverride的选项,如:
<Directory /home/*>
AllowOverride All
</Directory>

以上设置是默认的。

Apache 调优招数

, ,

这篇文章有时间真该翻译一下。

Apache tune-up tips:

1.Upgrade Apache! The newest version contains several performance enhancements.

2.In httpd.conf, set "HostNameLookups off" which avoids doing a reverse DNS lookup on every visitor who hits your web site.

3.In httpd.conf, set "MaxClients 230" or higher for busier web sites. This allows more httpd daemons to run simultaneously and avoids clogging up the process queue. [Don't increase MaxClients to greater than your available RAM! Figure betwee 2 - 8 MB per client. 230 clients may require roughly 1 GB availableRAM].

4.Serve web graphics (such as GIF files) from another machine.

5.Make sure your web pages and CGI pages are browser cache friendly. See the "Caching Tutorial for Web Authors and Webmasters" at http://www.pobox.com/~mnot/cache_docs/ [or here: http://www.mnot.net/cache_docs/ or here: cache_docs/"]

6.Keep your Apache lean and mean. Compile Apache with as few modules as needed. Before compiling (before your run make), edit the /apache_1.x.x/src/Configuration file put a # in front of any AddModule lines you don't need.

7.If you don't need traffic logs (such as a site that only serves graphics) then use the TransferLog directive in httpd.conf to redirect log entries to /dev/null/

8.Unless you insist on using .htaccess files to control access to certain directories (there are other ways to do that), in access.conf (or httpd.conf in newer versions of Apache) in the section, set "AllowOverride None" so that Apache will not bother looking for an .htaccess file in each directory with each request.

9.DO NOT leave unnecessary background processes running. Removing extraneous background tasks not only improves performance but security as well. In the /etc/rc.d/rc3.d/ directory [on other systems, this may be different, for example, with Debian, it is /etc/rc2.d/. -D.], delete symlinks to processes you don't need to run. For a plain vanilla local disk web server in Linux, you should only need routed, network, inet, httpd, and local symlinks in your /etc/rc.d/rc3.d/ directory. Reboot the machine if you change the contents of that directory.

10.DO NOT serve web pages or write web traffic logs on a networked disk drive (ie. NFS networked disks) -- read and write to local disk drives only. NFS I/O operations incure huge overhead.

11.DO NOT run Apache (httpd) via the tcpd wrapper in /etc/inetd.conf. Apache can be started when the machine boots by either adding the startup command to your rc.local file or by placing the httpd startup script to your /etc/rc.d/rc3.d/ directory. If you want some mechanism to block requests by IP address then use the "deny from" directive in the Apache's conf files or in a .htacess file.

12.DO NOT leave X Windows running on your web server if you're not using it -- just be sure to Ctrl-Alt-Backspace to close the X session when you're done using it.

13.Avoid using SSI tags. [From http://www.squid-cache.org/mail-archive/squid-users/199901/0080.html It might be worth noting that SSI pages can be made cacheable by using XBitHack full, with the appropriate x-bit settings. This doesn't specifically control the expiry date or cache-control headers, but Apache won't be generating anything that's actively harmful to cacheing in that respect; the proxy will apply its usual rules based on the last-modified header that's then generated based on the source file. AFAIK this _does_ work in practice with squid (whereas the "conventional" way of enabling SSI will result in the documents appearing to be uncacheable). ]

14.In CGI scripts:
o File I/O: Open as few files as possible. Be sure to explicetly close each opened file. Stop reading the file as soon as you found the data you need. Consider structuring data files into fixed-length fields and using read() function to skip ahead to just the part of the file you need to read.
o Shell Commands: Call shell commands via their full path: eg. use '/bin/date' instead of just `date` in a perl script.
o If your site is mostly CGI driven, by all means use mod_perl. See http://perl.apache.org/
o Perl programmers should study "Effective Perl Programming" by Joseph N. Hall (an Addison Wesley book) and "The Perl Cookbook" by Tom Christiansen (an O'Reilly book) -- two good texts for optimizing perl code. For example, you can preallocate the memory for a hash that will contain 256 items like so: keys(%names) = 256;
o Avoid having more than 1000 files in your web page directory. Organize your web page files into subdirectories. The more files there are in a directory, the longer it takes to locate that file during a request.

15.Put as few graphics in your web pages as possible. Make sure each image is run through an image compressor.

16.Stress test your web site. Run Apache Benchmark program (called "ab") in Apache's /bin or /sbin directory. The ab program will simulate heavy traffic by running multiple simultaneous requests on any web page you want for as long as you want then measures the load and response times. Very useful for measuring the effects of your tuning efforts.

17.For best performance, unplug the network cable from your web server -- the load will drop down to zero almost instantly! ;-)

18.Set the 'noatime' mount option (in /etc/fstab) on your htdocs partition.

19.If you have a seperate partition for /tmp, you should set its mount options (in /etc/fstab) to nodev,noexec,nosuid. Doing so will add a bit more protection against hackers dropping a zombie bot in your /tmp and running it.

20.Consider using mod_gzip (or mod_deflate for Apache 2), or even pre-compressing static pages on disk.

21.Set KeepAliveTimeout to about 2 seconds. This offers the client enough time to request all files needed for a page load while ensuring that spare servers aren't unduly prevented from serving new client requests should there be a heavy load.

22.Disable ExtendedStatus unless you're actually debugging. Same goes for mod_info.

原文见: http://users.encs.concordia.ca/~daniel/tips/apache_tuning.html
November 2009
S M T W T F S
October 2009December 2009
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30