服务器

.htaccess常用设置

.htaccess 文件 (Hypertext Access file) 是Apache Web服务器的一个非常强大的配置文件,对于这个文件,Apache有一堆参数可以让你配置出几乎随心所欲的能。.htaccess 配置文件坚持了Unix的一个文化——使用一个ASCII 的纯文本文件来配置你的网站的访问策略。

1. 创建自定义的出错页面

对于Linux Apache来说这是一项极其简单的事情。使用下面的.htaccess语法你可以轻松的完成这一功能。(把.htaccess放在你的网站根目录下)

ErrorDocument 401 /error/401.php
ErrorDocument 403 /error/403.php
ErrorDocument 404 /error/404.php
ErrorDocument 500 /error/500.php

2. 设置网站的时区

SetEnv TZ America/Houston

3. 阻止IP列表

有些时候,你需要以IP地址的方式阻止一些访问。无论是对于一个IP地址还是一个网段,这都是一件非常简单的事情,如下所示:

allow from all
deny from 145.186.14.122
deny from 210.10.56 #封禁210.10.56.0~210.10.56.255的所有IP地址

Apache对于被拒绝的IP会返回403错误。

4. 把一些老的链接转到新的链接上——搜索引擎优化SEO

Redirect 301 /iindex.php  http://www.njava.com

5. 为服务器管理员设置电子邮件。

ServerSignature EMail
SetEnv SERVER_ADMINdefault@domain.com

6. 使用.htaccess 访止盗链。

如果你网站上的一个图片被别的N多的网站引用了,那么,这很有可能会导致你服务器的性能下降,使用下面的代码可以保护某些热门的链接不被过多的引用。

Options +FollowSymlinks
# Protect Hotlinking
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www.)?domainname.com/[nc]
RewriteRule .*.(gif|jpg|png)$http://www.someonename.com/Article/UploadFiles/200908/20090824122550889.png[nc]

7. 阻止 User Agent 的所有请求

## .htaccess Code :: BEGIN
## Block Bad Bots by user-Agent
SetEnvIfNoCase user-Agent ^FrontPage [NC,OR]
SetEnvIfNoCase user-Agent ^Java.* [NC,OR]
SetEnvIfNoCase user-Agent ^Microsoft.URL [NC,OR]
SetEnvIfNoCase user-Agent ^MSFrontPage [NC,OR]
SetEnvIfNoCase user-Agent ^Offline.Explorer [NC,OR]
SetEnvIfNoCase user-Agent ^[Ww]eb[Bb]andit [NC,OR]
SetEnvIfNoCase user-Agent ^Zeus [NC]

Order Allow,Deny
Allow from all
Deny from env=bad_bot

## .htaccess Code :: END

8. 把某些特殊的IP地址的请求重定向到别的站点

ErrorDocument 403http://www.youdomain.com
Order deny,allow
Deny from all
Allow from 124.34.48.165
Allow from 102.54.68.123

9. 直接找开文件而不是下载

通常,我们打开网上文件的时候总是会出现一个对话框问我们是下载还是直接打开,使用下面的设置就不会出现这个问题了,直接打开。

AddType application/octet-stream .pdf
AddType application/octet-stream .zip
AddType application/octet-stream .mov

10. 修改文件类型

下面的示例可以让任何的文件都成为PHP那么被服务器解释。比如:myphp, cgi,phtml等。

ForceType application/x-httpd-php
SetHandler application/x-httpd-php

11. 阻止存取.htaccess 文件

# secure htaccess file
order allow,deny
deny from all

12. 保护服务器上的文件被存取

# prevent access of a certain fileorder allow,deny
deny from all

13. 阻止目录浏览

# disable directory brow
sing
Options All -Indexes

14. 设置默认主页

# serve alternate default index page
DirectoryIndex about.html

15. 口令认证

你可以创建一个文件用于认证。下面是一个示例:

# to protect a file
AuthType Basic
AuthName “Prompt”
AuthUserFile /home/path/.htpasswd
Require valid-user

# password-protect a directory resides
AuthType basic
AuthName “This directory is protected”
AuthUserFile /home/path/.htpasswd
AuthGroupFile /dev/null
Require valid-user

16. 把老的域名转像新的域名

# redirect from old domain to new domain
RewriteEngine On
RewriteRule ^(.*)$http://www.yourdomain.com/$1[R=301,L]

Tags: , ,

星期四, 三月 11th, 2010 服务器 评论暂缺

apache DDos防范模块 mod_evasive

什么是mod_evasive?

mod_evasive is an evasive maneuvers module for Apache to provide evasive action in the event of an HTTP DoS or DDoS attack or brute force attack. It is also designed to be a detection and network management tool, and can be easily configured to talk to ipchains, firewalls, routers, and etcetera. mod_evasive presently reports abuses via email and syslog facilities.

Detection is performed by creating an internal dynamic hash table of IP Addresses and URIs, and denying any single IP address from any of the following:

  • Requesting the same page more than a few times per second
  • Making more than 50 concurrent requests on the same child per second
  • Making any requests while temporarily blacklisted (on a blocking list)

This method has worked well in both single-server script attacks as well as distributed attacks, but just like other evasive tools, is only as useful to the point of bandwidth and processor consumption (e.g. the amount of bandwidth and processor required to receive/process/respond to invalid requests), which is why it’s a good idea to integrate this with your firewalls and routers for maximum protection.

This module instantiates for each listener individually, and therefore has a built-in cleanup mechanism and scaling capabilities. Because of this per-child design, legitimate requests are never compromised (even from proxies and NAT addresses) but only scripted attacks. Even a user repeatedly clicking on ‘reload’ should not be affected unless they do it maliciously. mod_evasive is fully tweakable through the Apache configuration file, easy to incorporate into your web server, and easy to use.

官方网站:http://www.nuclearelephant.com/projects/mod_evasive/

原理

mod_evasive是apache防范DDOS攻击的模块,其原理大致如下:
有新访问到达时:

  • 查看黑名单中是否有该客户IP。
  • 将IP和请求URL一起HASH;查找HASH表看过去1秒是否连续请求同一页。
  • 将IP和请求URL一起HASH;查找HASH表看过去1秒是否请求超过50个连接。

满足任意一条就返回403并阻止该IP一定时间,该时间由DOSSiteInterval决定。

1、安装mod_evasive

bear@bear-laptop:~$ sudo apt-get install libapache2-mod-e
libapache2-mod-encoding  libapache2-mod-evasive
bear@bear-laptop:~$ sudo apt-get install libapache2-mod-evasive
[sudo] password for bear:
正在读取软件包列表… 完成
正在分析软件包的依赖关系树
正在读取状态信息… 完成
下列软件包是自动安装的并且现在不再被使用了:
linux-headers-2.6.31-14 linux-headers-2.6.31-14-generic
使用’apt-get autoremove’来删除它们
下列【新】软件包将被安装:
libapache2-mod-evasive
共升级了 0 个软件包,新安装了 1 个软件包,要卸载 0 个软件包,有 0 个软件未被升级。
需要下载 15.9kB 的软件包。
解压缩后会消耗掉 115kB 的额外空间。
获取:1 http://ubuntu.cn99.com karmic/universe libapache2-mod-evasive 1.10.1-1 [15.9kB]
下载 15.9kB,耗时 0 秒 (121kB/s)
选中了曾被取消选择的软件包 libapache2-mod-evasive。
(正在读取数据库 … 系统当前总共安装有 151313 个文件和目录。)
正在解压缩 libapache2-mod-evasive (从 …/libapache2-mod-evasive_1.10.1-1_amd64.deb) …
正在设置 libapache2-mod-evasive (1.10.1-1) …
* Reloading web server config apache2                                          apache2: Could not reliably determine the server’s fully qualified domain name, using 127.0.1.1 for ServerName
[ OK ]

bear@bear-laptop:~$

2、配置mod_evasive

sudo vi /etc/apache/conf.d/mod_evasive

#添加以下:

<IfModule mod_evasive20.c>

DOSHashTableSize 3097:定义哈希表大小。

DOSSiteCount 50:允许客户机的最大并发连接。

DOSPageCount 2:允许客户机访问同一页的间隔。

DOSPageInterval 1:网页访问计数器间隔。

DOSSiteInterval 1:全站访问计数器间隔。

DOSSiteInterval 60:加入黑名单后拒绝访问时间。

DOSEmailNotify crdd1130@gmail.com:有IP加入黑名单后通知管理员。

DOSSystemCommand "sudo iptables -A INPUT -s %s -j DROP":IP加入黑名单后执行的系统命令。

DOSLogDir "/tmp":锁定机制临时目录。

DOSWhiteList 127.0.0.1:防范白名单,不阻止白名单IP。

</IfModule>


Tags: ,

星期四, 三月 11th, 2010 服务器 评论暂缺

SHELL下的数字比较及计算

比较:
方法一: if [ ${A} -lt ${B} ]; then …
这是最基本的比较方法,使用lt(小于),gt(大于),le(小于等于),ge(大于等于),优点:还没发现;缺点:只能比较整数,使用lt,gt等不直观
方法二: if ((${A} < ${B})) then …
这是CShell风格比较,优点:不用使用lt,gt等难记的字符串;缺点:还是只能比较整数
方法三: if (echo ${A} ${B} | awk ‘!($1>$2){exit 1}’) then …
这是使用awk比较,优点:可以比较小数;缺点:表达式太复杂,难记
方法四: if (echo ${A} – ${B} | bc -q | grep -q “^-”); then …
这是使用bc计算比较,优点:可以比较小数;缺点:表达式更复杂,难记

计算:
方法一:typeset C=$(expr ${A} + ${B});
SHELL中的基本工具,优点:方便检测变量是否为数字;缺点:只能计算整数,且只能计算加减法,不能计算乘除法
方法二:let “C=${A}+${B}”; 或 let “C=A+B”
内嵌命令计算,优点:能计算乘除法及位运算等;缺点:只能计算整数
方法三:typeset C=$((A+B))
CShell风格的计算,优点:能计算乘除法及位运算等,简介,编写方便;缺点:不能计算小数
方法四:typeset C=${echo ${A} ${B} | awk ‘{print $1+$2}’)
使用awk计算,优点:能计算小数,可以实现多种计算方式,计算灵活;缺点:表达式太复杂
方法五:typeset C=${echo ${A} + ${B} | bc -q)
使用awk计算,优点:能计算小数,计算方式比awk还多,计算灵活;缺点:表达式太复杂,小数点后面的位数必须使用scale=N来设置,否则可能会将结果截断为整数

Tags: , ,

星期四, 三月 11th, 2010 服务器 评论暂缺

查看Apache并发请求数及其TCP连接状态

# prefork MPM
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves

StartServers     10
MinSpareServers   10
MaxSpareServers   15
ServerLimit     2000
MaxClients      2000
MaxRequestsPerChild 10000

查看httpd进程数(即prefork模式下Apache能够处理的并发请求数):

Linux命令:

ps -ef | grep httpd | wc -l

返回结果示例:

1388

表示Apache能够处理1388个并发请求,这个值Apache可根据负载情况自动调整,我这组服务器中每台的峰值曾达到过2002。

查看Apache的并发请求数及其TCP连接状态:

Linux命令:

netstat -n | awk ‘/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}’

(这条语句是从新浪互动社区事业部技术总监王老大那儿获得的,非常不错)

返回结果示例:

LAST_ACK 5

SYN_RECV 30

ESTABLISHED 1597

FIN_WAIT1 51

FIN_WAIT2 504

TIME_WAIT 1057

其中的SYN_RECV表示正在等待处理的请求数;ESTABLISHED表示正常数据传输状态;TIME_WAIT表示处理完毕,等待超时结束的请求数。

关于TCP状态的变迁,可以从下图形象地看出:

状态:描述

CLOSED:无连接是活动的或正在进行

LISTEN:服务器在等待进入呼叫

SYN_RECV:一个连接请求已经到达,等待确认

SYN_SENT:应用已经开始,打开一个连接

ESTABLISHED:正常数据传输状态

FIN_WAIT1:应用说它已经完成

FIN_WAIT2:另一边已同意释放

ITMED_WAIT:等待所有分组死掉

CLOSING:两边同时尝试关闭

TIME_WAIT:另一边已初始化一个释放

LAST_ACK:等待所有分组死掉

Tags: , ,

星期四, 三月 11th, 2010 服务器 评论暂缺

MySQL数据库命令行修改root密码的几种方法

方法1: 用SET PASSWORD命令
mysql -u root
mysql> SET PASSWORD FOR ‘root’@’localhost’ = PASSWORD(’newpass’);

方法2:用mysqladmin
mysqladmin -u root password “newpass”
如果root已经设置过密码,采用如下方法
mysqladmin -u root password oldpass “newpass”

方法3: 用UPDATE直接编辑user表
mysql -u root
mysql> use mysql;
mysql> UPDATE user SET Password = PASSWORD(’newpass’) WHERE user = ‘root’;
mysql> FLUSH PRIVILEGES;

在丢失root密码的时候,可以这样
mysqld_safe –skip-grant-tables&
mysql -u root mysql
mysql> UPDATE user SET password=PASSWORD(”new password”) WHERE user=’root’;
mysql> FLUSH PRIVILEGES;

Tags: ,

星期四, 三月 11th, 2010 服务器 评论暂缺

优化Http header信息

curl -I yourdomain.com 能看到什么? Server: Apache xxx PHP xxx XXX xxx ,明码实价,一字排开。这是干嘛,卖菜呢?

我们不妨看看 curl -I www.google.com 结果如何:

HTTP/1.1 302 Found
Cache-Control: private
Location: http://sorry.google.com/sorry/?continue=http://www.google.com/
Date: Mon, 12 Jan 2009 06:57:41 GMT
Content-Type: text/html; charset=UTF-8
Server: GFE/1.3
Content-Length: 259

请注意这里 Google 的前端 Web Server 是 GFE/1.3 (Google Front Edge 1.3),至于它具体对应 Apache 1.3.x 还是 Windows 1.3,我们并不知晓。这样就起到了很好的信息隐藏作用,一旦网上发现 Apache 1.3.x 或者 Windows 1.3 的最新漏洞,黑客们并不会直接联想到 GFE/1.3,自然也就不会来多作尝试了。

所以,我们应该把这些不可告人的秘密都隐藏起来,哪怕放一段文字广告(如: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]),也比卖菜似的一一详细罗列版本要好。

参考解决方案:

1. Lighttpd 1.4.20

src/response.c:108 改为:

buffer_append_string_len(b, CONST_STR_LEN(“\r\nServer: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]“));

输出 Header:
HTTP/1.1 404 Not Found
Content-Type: text/html
Content-Length: 345
Date: Mon, 12 Jan 2009 13:54:02 GMT
Server: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]

2. Nginx 0.7.30

src/http/ngx_http_header_filter_module.c:48-49 改为:

static char ngx_http_server_string[] = “Server: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]” CRLF;
static char ngx_http_server_full_string[] = “Server: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]” CRLF;

输出 Header:
HTTP/1.1 200 OK
Server: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]
Date: Mon, 12 Jan 2009 14:01:10 GMT
Content-Type: text/html
Content-Length: 151
Last-Modified: Mon, 12 Jan 2009 14:00:56 GMT
Connection: keep-alive
Accept-Ranges: bytes

3. Cherokee 0.11.6

cherokee/version.c:93 添加:

ret = cherokee_buffer_add_str (buf, “[AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]“);
return ret;

输出 Header:
HTTP/1.1 200 OK
Connection: Keep-Alive
Keep-Alive: timeout=15
Date: Mon, 12 Jan 2009 14:54:39 GMT
Server: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]
ETag: 496b54af=703
Last-Modified: Mon, 12 Jan 2009 14:33:19 GMT
Content-Type: text/html
Content-Length: 1795

4. Apache 2.2.11

server/core.c:2784 添加:

ap_add_version_component(pconf, “[AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]“);
return;

输出 Header:
HTTP/1.1 200 OK
Date: Mon, 12 Jan 2009 14:28:10 GMT
Server: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]
Last-Modified: Sat, 20 Nov 2004 20:16:24 GMT
ETag: “1920edd-2c-3e9564c23b600″
Accept-Ranges: bytes
Content-Length: 44
Content-Type: text/html

5. Squid 3.0 STABLE 11

src/globals.cc:58 改为:

const char *const full_appname_string = “[AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]“;

输出 Header:
HTTP/1.0 400 Bad Request
Server: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]
Mime-Version: 1.0
Date: Mon, 12 Jan 2009 15:25:15 GMT
Content-Type: text/html
Content-Length: 1553
Expires: Mon, 12 Jan 2009 15:25:15 GMT
X-Squid-Error: ERR_INVALID_URL 0
X-Cache: MISS from ‘cache.hutuworm.org’
Via: 1.0 ‘cache.hutuworm.org’ ([AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ])
Proxy-Connection: close

6. Tomcat 6.0.18

java/org/apache/coyote/http11/Constants.java:56 和 java/org/apache/coyote/ajp/Constants.java:236 均改为:

ByteChunk.convertToBytes(“Server: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]” + CRLF);

输出 Header:
HTTP/1.1 200 OK
Server: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]
ETag: W/”7857-1216684872000″
Last-Modified: Tue, 22 Jul 2008 00:01:12 GMT
Content-Type: text/html
Content-Length: 7857
Date: Mon, 12 Jan 2009 16:30:44 GMT

7. JBoss 5.0.0 GA

a. tomcat/src/resources/web.xml:40 改为

[AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]

b. 下载 JBoss Web Server 2.1.1.GA srctar (http://www.jboss.org/jbossweb/downloads/jboss-web/)

java/org/apache/coyote/http11/Constants.java:56 和 java/org/apache/coyote/ajp/Constants.java:236 均改为:

ByteChunk.convertToBytes(“Server: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]” + CRLF);

将编译所得 jbossweb.jar 覆盖 JBoss 编译输出文件:

JBOSS_SRC/build/output/jboss-5.0.0.GA/server/all/deploy/jbossweb.sar/jbossweb.jar
JBOSS_SRC/build/output/jboss-5.0.0.GA/server/standard/deploy/jbossweb.sar/jbossweb.jar
JBOSS_SRC/build/output/jboss-5.0.0.GA/server/default/deploy/jbossweb.sar/jbossweb.jar
JBOSS_SRC/build/output/jboss-5.0.0.GA/server/web/deploy/jbossweb.sar/jbossweb.jar

输出 Header:
HTTP/1.1 200 OK
Server: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]
X-Powered-By: [AD: DangDang http://tinyurl.com/2dangdang ][ Your AD Here ][AD: Joyo http://tinyurl.com/2amazon ]
Accept-Ranges: bytes
ETag: W/”1581-1231842222000″
Last-Modified: Tue, 13 Jan 2009 10:23:42 GMT
Content-Type: text/html
Content-Length: 1581
Date: Tue, 13 Jan 2009 10:30:42 GM

Tags: ,

星期四, 三月 11th, 2010 服务器 评论暂缺

使用 Nginx 提升网站访问速度

本文主要介绍如何在 Linux 系统上安装高性能的 HTTP 服务器 —— Nginx、并在不改变原有网站结构的条件下用 Nginx 来提升网站的访问速度。
Nginx 简介
Nginx(“engine x”) 是一个高性能的 HTTP 和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器。 Nginx是由 Igor Sysoev 为俄罗斯访问量第二的 Rambler.ru 站点开发的,它已经在该站点运行超过两年半了。 Igor 将源代码以类BSD 许可证的形式发布。尽管还是测试版,但是,Nginx 已经因为它的稳定性、丰富的功能集、示例配置文件和低系统资源的消耗而闻名了。
根据最新一期(08 年 6 月份)的 NetCraft 调查报告显示,已经有超过两百万的主机使用了 Nginx,这个数字超过了另外一个轻量级的 HTTP 服务器 lighttpd, 排名第四,并且发展迅速。下面是这份报告的前几名的报表:
以下为引用的内容:
产品         网站数
Apache  84,309,103
IIS  60,987,087
Google GFE  10,465,178
Unknown  4,903,174
nginx  2,125,160
Oversee  1,953,848
lighttpd  1,532,952

关于这期调查报告的更详细信息请看下面链接:

http://survey.netcraft.com/Reports/200806/

下图是最近几个月使用 Nginx 和 lighttpd 的网站数比较

图 1. 最近几个月使用 Nginx 和 lighttpd 的网站数比较

使用 Nginx 前必须了解的事项

目前官方 Nginx 并不支持 Windows,您只能在包括 Linux、UNIX、BSD 系统下安装和使用;
Nginx 本身只是一个 HTTP 和反向代理服务器,它无法像 Apache 一样通过安装各种模块来支持不同的页面脚本,例如 PHP、CGI 等;
Nginx 支持简单的负载均衡和容错;
支持作为基本 HTTP 服务器的功能,例如日志、压缩、Byte ranges、Chunked responses、SSL、虚拟主机等等,应有尽有。
在 Linux 下安装 Nginx
为了确保能在 Nginx 中使用正则表达式进行更灵活的配置,安装之前需要确定系统是否安装有 PCRE(Perl Compatible Regular Expressions)包。您可以到 ftp://ftp.csx.cam.ac.uk/pub/software/programming/pcre/ 下载最新的 PCRE 源码包,使用下面命令下载编译和安装 PCRE 包:
# wget ftp://ftp.csx.cam.ac.uk/pub/soft … cre/pcre-7.7.tar.gz
# tar zxvf pcre-7.7.tar.gz
# cd pcre-7.7
# ./configure
# make
# make install

接下来安装 Nginx,Nginx 一般有两个版本,分别是稳定版和开发版,您可以根据您的目的来选择这两个版本的其中一个,下面是把 Nginx 安装到 /opt/nginx 目录下的详细步骤:
# wget http://sysoev.ru/nginx/nginx-0.6.31.tar.gz
# tar zxvf nginx-0.6.31.tar.gz
# cd nginx-0.6.31
# ./configure –with-http_stub_status_module –prefix=/opt/nginx
# make
# make install

其中参数 –with-http_stub_status_module 是为了启用 nginx 的 NginxStatus 功能,用来监控 Nginx 的当前状态。
安装成功后 /opt/nginx 目录下有四个子目录分别是:conf、html、logs、sbin 。其中 Nginx 的配置文件存放于conf/nginx.conf,Nginx 只有一个程序文件位于 sbin 目录下的 nginx 文件。确保系统的 80端口没被其他程序占用,运行 sbin/nginx 命令来启动 Nginx,打开浏览器访问此机器的 IP,如果浏览器出现 Welcome tonginx! 则表示 Nginx 已经安装并运行成功。
常用的 Nginx 参数和控制
程序运行参数
Nginx 安装后只有一个程序文件,本身并不提供各种管理程序,它是使用参数和系统信号机制对 Nginx 进程本身进行控制的。 Nginx 的参数包括有如下几个:
-c <path_to_config>:使用指定的配置文件而不是 conf 目录下的 nginx.conf 。
-t:测试配置文件是否正确,在运行时需要重新加载配置的时候,此命令非常重要,用来检测所修改的配置文件是否有语法错误。
-v:显示 nginx 版本号。
-V:显示 nginx 的版本号以及编译环境信息以及编译时的参数。
例如我们要测试某个配置文件是否书写正确,我们可以使用以下命令
sbin/nginx – t – c conf/nginx2.conf
通过信号对 Nginx 进行控制
Nginx 支持下表中的信号:
信号名                                             作用描述
TERM, INT  快速关闭程序,中止当前正在处理的请求
QUIT  处理完当前请求后,关闭程序
HUP  重新加载配置,并开启新的工作进程,关闭就的进程,此操作不会中断请求
USR1  重新打开日志文件,用于切换日志,例如每天生成一个新的日志文件
USR2  平滑升级可执行程序
WINCH  从容关闭工作进程
有两种方式来通过这些信号去控制 Nginx,第一是通过 logs 目录下的 nginx.pid 查看当前运行的 Nginx 的进程 ID,通过 kill – XXX <pid> 来控制 Nginx,其中 XXX 就是上表中列出的信号名。如果您的系统中只有一个 Nginx 进程,那您也可以通过 killall 命令来完成,例如运行 killall – s HUP nginx 来让 Nginx 重新加载配置。
配置 Nginx
先来看一个实际的配置文件:

以下为引用的内容:
user  nobody;# 工作进程的属主
worker_processes  4;# 工作进程数,一般与 CPU 核数等同 #error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
#pid        logs/nginx.pid;
events {
use epoll;#Linux 下性能最好的 event 模式
worker_connections  2048;# 每个工作进程允许最大的同时连接数
}
http {
include       mime.types;
default_type  application/octet-stream;
#log_format  main  ‘$remote_addr – $remote_user [$time_local] $request ‘
#                  ‘”$status” $body_bytes_sent “$http_referer” ‘
#                  ‘”$http_user_agent” “$http_x_forwarded_for”‘;
#access_log  off;
access_log  logs/access.log;# 日志文件名
sendfile        on;
#tcp_nopush     on;
tcp_nodelay     on;
keepalive_timeout  65;
include          gzip.conf;

# 集群中的所有后台服务器的配置信息
upstream tomcats {
server 192.168.0.11:8080 weight=10;
server 192.168.0.11:8081 weight=10;
server 192.168.0.12:8080 weight=10;
server 192.168.0.12:8081 weight=10;
server 192.168.0.13:8080 weight=10;
server 192.168.0.13:8081 weight=10;
}
server {
listen       80;#HTTP 的端口
server_name  localhost;
charset utf-8;
#access_log  logs/host.access.log  main;
location ~ ^/NginxStatus/ {
stub_status on; #Nginx 状态监控配置
access_log off;
}
location ~ ^/(WEB-INF)/ {
deny all;
}

location ~ \.(htm|html|asp|php|gif|jpg|jpeg|png|bmp|ico|rar|css|js|
zip|java|jar|txt|flv|swf|mid|doc|ppt|xls|pdf|txt|mp3|wma)$ {
root /opt/webapp;
expires 24h;
}
location / {
proxy_pass http://tomcats;# 反向代理
include proxy.conf;
}
error_page 404 /html/404.html;
# redirect server error pages to the static page /50x.html
#
error_page 502 503 /html/502.html;
error_page 500 504 /50x.html;
location = /50x.html {
root   html;
}
}
}

Nginx 监控
上面是一个实际网站的配置实例,其中灰色文字为配置说明。上述配置中,首先我们定义了一个 location ~^/NginxStatus/,这样通过 http://localhost/NginxStatus/ 就可以监控到 Nginx的运行信息,显示的内容如下:
以下为引用的内容:
Active connections: 70
server accepts handled requests
14553819 14553819 19239266
Reading: 0 Writing: 3 Waiting: 67

NginxStatus 显示的内容意思如下:

active connections – 当前 Nginx 正处理的活动连接数。
erveraccepts handled requests — 总共处理了 14553819 个连接 , 成功创建 14553819 次握手 (证明中间没有失败的 ), 总共处理了 19239266 个请求 ( 平均每次握手处理了 1.3 个数据请求 )。
reading — nginx 读取到客户端的 Header 信息数。
writing — nginx 返回给客户端的 Header 信息数。
waiting — 开启 keep-alive 的情况下,这个值等于 active – (reading + writing),意思就是 Nginx 已经处理完正在等候下一次请求指令的驻留连接。
静态文件处理
通过正则表达式,我们可让 Nginx 识别出各种静态文件,例如 images 路径下的所有请求可以写为:
以下为引用的内容:
location ~ ^/images/ {
root /opt/webapp/images;
}
而下面的配置则定义了几种文件类型的请求处理方式。
location ~ \.(htm|html|gif|jpg|jpeg|png|bmp|ico|css|js|txt)$ {
root /opt/webapp;
expires 24h;
}

对于例如图片、静态 HTML 文件、js 脚本文件和 css 样式文件等,我们希望 Nginx 直接处理并返回给浏览器,这样可以大大的加快网页浏览时的速度。因此对于这类文件我们需要通过 root 指令来指定文件的存放路径,同时因为这类文件并不常修改,通过 expires 指令来控制其在浏览器的缓存,以减少不必要的请求。 expires 指令可以控制 HTTP 应答中的“ Expires ”和“ Cache-Control ”的头标(起到控制页面缓存的作用)。您可以使用例如以下的格式来书写 Expires:
以下为引用的内容:
expires 1 January, 1970, 00:00:01 GMT;
expires 60s;
expires 30m;
expires 24h;
expires 1d;
expires max;
expires off;

动态页面请求处理
Nginx本身并不支持现在流行的 JSP、ASP、PHP、PERL 等动态页面,但是它可以通过反向代理将请求发送到后端的服务器,例如Tomcat、Apache、IIS 等来完成动态页面的请求处理。前面的配置示例中,我们首先定义了由 Nginx直接处理的一些静态文件请求后,其他所有的请求通过 proxy_pass 指令传送给后端的服务器(在上述例子中是 Tomcat)。最简单的 proxy_pass 用法如下:
以下为引用的内容:
location / {
proxy_pass        http://localhost:8080;
proxy_set_header  X-Real-IP  $remote_addr;
}

这里我们没有使用到集群,而是将请求直接送到运行在 8080 端口的 Tomcat 服务上来完成类似 JSP 和 Servlet 的请求处理。
当页面的访问量非常大的时候,往往需要多个应用服务器来共同承担动态页面的执行操作,这时我们就需要使用集群的架构。 Nginx 通过 upstream 指令来定义一个服务器的集群,最前面那个完整的例子中我们定义了一个名为 tomcats 的集群,这个集群中包括了三台服务器共 6 个 Tomcat 服务。而 proxy_pass 指令的写法变成了:
以下为引用的内容:
location / {
proxy_pass        http://tomcats;
proxy_set_header  X-Real-IP  $remote_addr;
}

在 Nginx 的集群配置中,Nginx 使用最简单的平均分配规则给集群中的每个节点分配请求。一旦某个节点失效时,或者重新起效时,Nginx 都会非常及时的处理状态的变化,以保证不会影响到用户的访问。
总结
尽管整个程序包只有五百多 K,但麻雀虽小、五脏俱全。 Nginx官方提供的各种功能模块应有尽有,结合这些模块可以完整各种各样的配置要求,例如:压缩、防盗链、集群、FastCGI、流媒体服务器、 Memcached 支持、URL 重写等等,更关键的是 Nginx 拥有 Apache 和其他 HTTP服务器无法比拟的高性能。您甚至可以在不改变原有网站的架构上,通过在前端引入 Nginx 来提升网站的访问速度。
本文只是简单介绍了 Nginx 的安装以及常见的基本的配置和使用,更多关于 Nginx 的信息请阅读文章后面的参考资源。在这里要非常感谢我的朋友——陈磊(chanix@msn.com),他一直在做 Nginx 的中文 WIKI(http://wiki.codemongers.com/NginxChs),同时也是他介绍给我这么好的一款软件。
如果您的网站是运行在 Linux 下,如果您并没有使用一些非常复杂的而且确定 Nginx 无法完成的功能,那您应该试试 Nginx 。

Tags: ,

星期四, 三月 11th, 2010 服务器 评论暂缺

Linux解决Too many open files的方法

Issue:
How do I set the maximum number of files allowed to be open on a system
Resolution:
The current setting for maximum number of open files can be viewed with the command:

ulimit -n

This number indicates the maximum number of files normal users (i.e. non-root) can have open in a single session. Note that for the root user, ulimit -n will sometimes output 1024 even after following the procedure to increase the maximum number of open files. This won’t effect root’s ability to open large numbers of files, as only normal users are bound by this value.

To increase the maximum number of open files beyond the default of 1024, two changes to the system may be necessary. In these examples, we will increase the maximum number of open files to the arbitrary value of 2048. All changes need to be made by the root user and users will need to log out and log back in before the changes will take effect.

1. Configure the system to accept the desired value for maximum number of open files Check the value in /proc/sys/fs/file-max to see if it is larger than the value needed for the maximum number of open files:

# cat /proc/sys/fs/file-max

If the value isn’t large enough, echo an appropriate number into the variable and add the change to /etc/sysctl.conf to make it persistent across reboots. If the number is already larger than the value you wish to use, skip to step 2.

# echo 2048 > /proc/sys/fs/file-max

and edit /etc/sysctl.conf to include the line:

fs.file-max = 2048

2. Set the value for maximum number of open files In the file /etc/security/limits.conf, below the commented line that reads

#<domain>      <type>  <item>         <value>

add this line:

* – nofile 2048

This line sets the default number of open file descriptors for every user on the system to 2048. Note that the “nofile” item has two possible limit values under the <type> header: hard and soft. Both types of limits must be set before the change in the maximum number of open files will take effect. By using the “-” character, both hard and soft limits are set simultaneously.

The hard limit represents the maximum value a soft limit may have and the soft limit represents the limit being actively enforced on the system at that time. Hard limits can be lowered by normal users, but not raised and soft limits cannot be set higher than hard limits. Only root may raise hard limits.

When increasing file limit descriptors, you may want to simply double the value. For example, if you need to increase the default value of 1024, increase the value to 2048 first. If you need to increase it again, try 4096, etc.

==================================================================
1。ulimit -a 查看系统目前资源限制的设定。
[root@test security]# ulimit -a
core file size        (blocks, -c) 0
data seg size         (kbytes, -d) unlimited
file size             (blocks, -f) unlimited
max locked memory     (kbytes, -l) unlimited
max memory size       (kbytes, -m) unlimited
open files                    (-n) 1024
pipe size          (512 bytes, -p) 8
stack size            (kbytes, -s) 8192
cpu time             (seconds, -t) unlimited
max user processes            (-u) 7168
virtual memory        (kbytes, -v) unlimited
[root@test security]#
通过以上命令,我们可以看到open files 的最大数为1024
那么我们可以通过一下命令修改该参数的最大值
2. ulimit -n 4096
[root@test security]# ulimit -n 4096
[root@test security]# ulimit -a
core file size        (blocks, -c) 0
data seg size         (kbytes, -d) unlimited
file size             (blocks, -f) unlimited
max locked memory     (kbytes, -l) unlimited
max memory size       (kbytes, -m) unlimited
open files                    (-n) 4096
pipe size          (512 bytes, -p) 8
stack size            (kbytes, -s) 8192
cpu time             (seconds, -t) unlimited
max user processes            (-u) 7168
virtual memory        (kbytes, -v) unlimited

这样我们就修改了系统在同一时间打开文件资源的最大数,基本解决以上问题。

另外我们可以通过lsof  -p [进程的 pid]来查看系统当前打开的文件资源,可以了解不同时期系统的文件资源的使用情况,可根据情况进行系统资源的配置。

Tags: ,

星期四, 三月 11th, 2010 服务器 评论暂缺

在linux下如何查看和踢除正在登陆的其它用户

使用who这个命令来查看当前正在登录的用户

[root@localhost http]# who
root     tty1         Apr  9 13:17
http     pts/0        Apr 16 15:13 (192.168.8.235)
http     pts/1        Apr 16 15:13 (192.168.8.235)

上面的消息告诉我们:tty是指在任何一个虚拟控制台登录则产生一个tty,比如你插上显示器登录主机,就会增加一个tty,那pts是什么呢?pts是每一个远程连接都会产生的

要踢出某个用户以及该用户运行的程序(很野蛮),请采用如下方法:

比如:想踢除http这个用户和他的所有开启的程序执行下面命令

pkill -u http

注意:这个命令实际上很危险,要相当小心的执行!!

说他危险的原因是:该用户所有有关的程序都会被关掉,那意味着什么呢?那意味着:如何你使用http这个用户开启的apache服务的 话,apache服务业停掉了,你必须手动开启apache服务!说得更严重点:如果你不小心执行了踢出root的命令,那意味着使用root开启的 ssh服务也停止了,你必须(是的!是必须!)接显示器到服务器上了,或者你必须按一下reset键了~~

那么安全的方法是什么呢?

安全的做法是先查看终端号,然后查看该终端执行的所有进程,根据进程号来停止服务!

示例:

[root@localhost http]# who
root     tty1         Apr  9 13:17
http     pts/0        Apr 16 15:13 (192.168.8.235)
[root@localhost http]# ps -ef|grep pts/0
http     16627 16595  0 15:13 ?        00:00:00 sshd: http@pts/0
http     16628 16627  0 15:13 pts/0    00:00:00 -bash
root     16680 16628  0 15:13 pts/0    00:00:00 su
root     16681 16680  0 15:13 pts/0    00:00:00 bash
root     18089 16681  0 15:41 pts/0    00:00:00 ps -ef
root     18090 16681  0 15:41 pts/0    00:00:00 grep pts/0

如果你要终止某个进程,看准进程号,执行。比如要敲掉http的bash,看准进程号是16628

Tags: ,

星期四, 三月 11th, 2010 服务器 评论暂缺

Apache缓存系统

Apache 从2.0开始就已经可以使用缓存模块了,不过在2.0的时候还是实验性的,到了2.2已经完全可以放心的使用。Apache 的缓存实现主要依靠 mod_cache、mod_disk_cache、mod_file_cache 及 mod_mem_cache。只需在配置编译的时候加上参数:–enable-cache、 –enable-disk-cache、–enable-file-cache、 –enable-mem-cache 即可。
关于 Apache 的编译安装本文就不再说了,可以参考以前的文章。这里主要介绍一下如何配置使用 Apache 的缓存功能。
具体来说,Apache 的缓存方式有两种,一种是基于硬盘文件的缓存,由 mod_disk_cache 实现,另一种是使用内存缓存,由 mod_mem_cache 实现,不过它们都是依赖 mod_cache 模块的,mod_cache 模块提供了一些缓存配置的指令供它们使用,而 mod_file_cache 模块是搭配 mod_mem_cache 模块使用的,下面分别进行介绍。
1、基于硬盘文件的缓存
基于硬盘文件存储的缓存由 mod_disk_cache 模块实现,先看个简单的配置例子:

CacheDefaultExpire 86400

CacheEnable disk /
CacheRoot /tmp/apacheCache
CacheDirLevels 5
CacheDirLength 5
CacheMaxFileSize 1048576
CacheMinFileSize 10

把上面的配置加到 Apache 的 httpd.conf 文件中,如果缓存相关的模块都已经编译进了 Apache 的核心,则无需加载模块,直接就能使用上面的指令。指令的详细说明如下:
CacheDefaultExpire: 设定缓存过期的时间(秒),默认是1小时,只有当缓存的文档没有设置过期时间或最后修改时间时这个指令才会生效
CacheEnable:启用缓存,第1个参数是缓存类弄,这里当然是 disk了,第2个参数是缓存路径,指的是 url 路径,这里是缓存所有的东西,直接写上“/”即可,如“/docs”则只缓存 /docs 下的所有文件
CacheRoot:缓存文件所在的目录,运行 Apache 的用户(如daemon 或 nobody)要能对其进行读写,如果不清楚的话可以直接设置成 777,请手动建立该目录并设置好访问权限
CacheDirLevels:缓存目录的深度,默认是3,这里设置为5
CacheDirLength:缓存目录名的字符长度,默认是4,这里设置为5
CacheMaxFileSize 和 CacheMaxFileSize:缓存文件的最大值和最小值(byte),当超过这个范围时将不再缓存,这里设置为 1M 和 10bytes
基于硬盘文件存储的文件基本上就这些内容,设置好后重启 Apache 应该就能使用了。一切正常的话,可以在缓存目录下看到 Apache 自动建立的一些目录和缓存的数据文件。
2、基于内存的缓存
基于内存的缓存主要由 mod_mem_cache 模块实现,还是看个简单的配置吧,这样比较直观:-)

CacheEnable mem /
MCacheMaxObjectCount 20000
MCacheMaxObjectSize 1048576
MCacheMaxStreamingBuffer 65536
MCacheMinObjectSize 10
MCacheRemovalAlgorithm GDSF
MCacheSize 131072

简单说一下上面一些指令的意思:
CacheEnable:启用缓存,使用基于内存的方式存储
MCacheMaxObjectCount:在内存中最多能存储缓存对象的个数,默认是1009,这里设置为20000
MCacheMaxObjectSize:单个缓存对象最大为 1M,默认是10000bytes
MCacheMaxStreamingBuffer:在缓冲区最多能够放置多少的将要被缓存对象的尺寸,这里设置为 65536,该值通常小于100000或 MCacheMaxObjectSize 设置的值
MCacheMinObjectSize:单个缓存对象最小为10bytes,默认为1bytes
MCacheRemovalAlgorithm:清除缓存所使用的算法,默认是 GDSF,还有一个是LRU,可以查一下 Apache 的官方文档,上面有些介绍
MCacheSize:缓存数据最多能使用的内存,单位是 kb,默认是100kb,这里设置为128M
保存重启 Apache 基于内存的缓存系统应该就能生效了,根据需要可以使基于内存的存储或硬盘文件的存储方式一起使用,只要指明不同的URL路径即可。
3、注意事项
使用缓存需要注意如下事项:
要使用缓存,必须使用指令 CacheEnable 启用它,目前可用的缓存类型为 disk 或 mem,禁止缓存可以使用 CacheDisable,如 CacheDisable /private
待缓存的 URL 返回的状态值必须为: 200、203、300、301 或 410
URL 的请求方式必须是 GET 方式
发送请求时,头部中包含 “Authorization: ”的字符串时,返回的内容将不会被缓存
URL 包含查询字符串,如问号?后的那些东西,除非返回的内容包含“Expires:”,否则不会被缓存
如果返回的状态值是 200,则返回的头部信息必须包含以下的一种才会被缓存:Etag、Last-Modified、Expires,除非设置了指令 CacheIgnoreNoLastMod On
如果返回内容的头部信息“Cache-Control:”中包含“private”,除非设置了指令 CacheStorePrivate On,否则不会被缓存
如果返回内容的头部信息“Cache-Control:”中包含“no-sotre”,除非设置了指令 CacheStoreNoStore On,否则不会被缓存
如果返回内容的头部信息“Vary:”中包含了“*”,不会被缓存
4、其它一些指令的介绍
如果你的网站有几个文件的访问非常频繁而又不经常变动,则可以在 Apache 启动的时候就把它们的内容缓存到内存中(当然要启用内存缓存系统),使用的是 mod_file_cache 模块,具体如下:
有多个文件可以用空格格开
MMapFile /var/www/html/index.html /var/www/html/articles/index.html
上面是缓存文件的内容到内存中,除此之外,还可以只缓存文件的打开句柄到内存中,当有请求进来的时候,Apache 直接从内存中获取文件的句柄,返回内容,和 MMapFile 指令很像,具体如下:
CacheFile /var/www/html/index.html /var/www/html/articles/index.html
上面两个指令所缓存的文件如果有修改的话,必须重启 Apache 或使用 graceful 之类的方式强制使 Apache 更新缓存数据,否则当用户访问的时候获取的不是最新的数据。
有时候需要根据某些特殊的头部信息来决定是否进行缓存,则可以使用如下指令:
当头部信息中包含 Set-Cookie 时则跳过不进行缓存操作
CacheIgnoreHeaders Set-Cookie
有时候需要缓存的时候跳过 URL 中的查询字符串?使用如下指令:
CacheIgnoreQueryString On
Apache 的缓存系统不仅可以缓存服务器本身的文件,也可以缓存通过代理得到的内容,对了,Apache 可以像 Squid 一样做代理,而且做的还不错,下篇文章就介绍一下 Apache 的代理功能吧。善用 Apache 的缓存功能,可以让你的网站速度提升不少。做为一个网站来说,虽然可用的各种缓存方案很多,但在 Web 服务器层做缓存的效率还是很值得一试的。

嗯 不过常用功能 nginx都有了 而且nginx效率更高
?nginx配合tomcat、resin等java应用服务器提供java支持
首先探讨一下为什么要使用nginx:

1、类似于apache+resin,nginx用于提供静态页面服务,比java服务器要强。虽然这些java服务器的性能都不赖,tomcat新版甚至还支持了epoll,但是用nginx来处理静态文件是一定比这些服务器更稳妥并更快速的。

2、nginx在配合java应用服务器时相比apache耦合度更低,所以它可以用相同的方式连上所有能支持http服务能力的java应用服 务器,无论是tomcat、resin、weblogic、jetty、websphere……,并且可以轻易地将一个应用同时连接不相同的服务器。譬如 一台跑tomcat,一台跑resin,这一点在切换或测试生产环境时非常有用。另外耦合度的降低,将使nginx和这些服务器之间的相互影响降到最低, 这样两者就能各尽其责,apache一般是采用一个模块来和java应用服务器打交道,这个模块是会对apache的运行或多或少产生影响的,nginx 告诉我们这些模块是多么的鸡肋,java服务器要不就往fastcgi协议支持方面发展会更好。

3、nginx的一些特性可以保住脆弱的java服务器。其中可以点名的:1是可细致定制的负载均衡策略;2是超强的故障屏蔽功能可以做到不遗漏任何一个请求;3是客户端连接的异步处理;4是比java服务器强上百倍的负荷能力。

综合这些优点,一般的java应用服务器,接上一个nginx后,在服务稳定性上将可匹敌数万美金的大型java集群服务器,java开发者就不用再为java性能方面发愁了。

Tags: , ,

星期四, 三月 11th, 2010 服务器 评论暂缺
Pages: Prev 1 2 3 4 5 6 7 Next