最近有点时间,在整理之前的文档时,给翻出来了,索性整理好顺边分享给大家,老鸟勿喷,菜鸟借鉴吧!

1、隐藏nginx版本号
隐藏前:
$ curl -I localhost
HTTP/1.1 200 OK
Server: nginx/1.6.3
Date: Fri, 16 Oct 2015 15:31:44 GMT
Content-Type: text/html
Content-Length: 18
Last-Modified: Wed, 07 Oct 2015 07:00:17 GMT
Connection: keep-alive
ETag: "5614c301-12"
Accept-Ranges: bytes

http {
server_tokens off; #在http标签内最前面加入"server_tokens off;"后保存退出
include mime.types;
/application/nginx/sbin/nginx -s reload #平滑重启nginx服务
隐藏后:
$ curl -I localhost
HTTP/1.1 200 OK
Server: nginx
Date: Fri, 16 Oct 2015 15:44:53 GMT
Content-Type: text/html
Content-Length: 18
Last-Modified: Wed, 07 Oct 2015 07:00:17 GMT
Connection: keep-alive
ETag: "5614c301-12"
Accept-Ranges: bytes

2、隐藏apache版本号
$ curl -I localhost
HTTP/1.1 200 OK
Date: Fri, 16 Oct 2015 15:57:01 GMT
Server: Apache/2.4.16 (Unix) PHP/5.6.12
X-Powered-By: PHP/5.6.12
Content-Type: text/html; charset=gb2312

2.1、打开httpd-default.conf模块
修改httpd.conf配置文件的476行,打开httpd-default.conf模块
$ vi /application/apache/conf/httpd.conf
476 # Include conf/extra/httpd-default.conf
修改为:476 Include conf/extra/httpd-default.conf #取消前面的#注释

2.2、修改httpd-default.conf文件
$ vi /application/apache/conf/extra/httpd-default.conf
在64行之后插入"ServerTokens Prod"
64 #
65 ServerTokens Prod #64行之后插入"ServerTokens Prod"
66 ServerSignature Off
$ /application/apache/bin/apachectl graceful #平滑重启apache服务
隐藏后:
$ curl -I localhost
HTTP/1.1 200 OK
Date: Fri, 16 Oct 2015 15:58:43 GMT
Server: Apache
X-Powered-By: PHP/5.6.12
Content-Type: text/html; charset=gb2312

3、更改掉nginx的默认用户及用户组nobody
$ useradd nginx -s /sbin/nologin -M #添加普通用户nginx,并且禁止它登录系统
更改默认用户的方法有两种:
第一种为:
$ grep "user" nginx.conf
user nginx nginx;
第二种为:
$ ./configure --user=nginx --group=nginx --prefix=/application/nginx-1.6.3 --with-http_stub_status_module --with-http_ssl_module
$ ps -ef|grep nginx
root 25404 1 0 Oct16 ? 00:00:00 nginx: master process /application/nginx/sbin/nginx
nginx 26092 25404 0 Oct16 ? 00:00:00 nginx: worker process

4、优化-根据硬件调整nginx子进程数
$ grep "worker_processes" nginx.conf
worker_processes 1; #worker_processes参数的设置可以等于cpu的个数或核数,进程数多一些,起始提供服务时就不会临时启动新进程提供服务,减少了系统开销,提升了服务速度。
查看linux服务器的CPU核数:
$ grep "physical id" /proc/cpuinfo
physical id : 0
$ vi nginx.conf
user nginx nginx;
worker_processes 4; #由默认的1调整为4
$ /application/nginx/sbin/nginx -s reload
$ ps -ef|grep nginx|grep -v grep
root 25404 1 0 Oct16 ? 00:00:00 nginx: master process /application/nginx/sbin/nginx
nginx 26185 25404 0 00:53 ? 00:00:00 nginx: worker process
nginx 26186 25404 0 00:53 ? 00:00:00 nginx: worker process
nginx 26187 25404 0 00:53 ? 00:00:00 nginx: worker process
nginx 26188 25404 0 00:53 ? 00:00:00 nginx: worker process

5、根据cpu核数优化cpu资源分配给不同的nginx进程
输入top后按1,查看cpu核数
$ grep "worker_cpu_affinity" nginx.conf
worker_cpu_affinity 0001 0010 0100 1000;
#worker_cpu_affinity就是配置nginx进程CPU亲和力的参数,即把不同的进程分给不同的CPU处理。这里0001 0010 0100 1000是掩码,分别代表1、2、3、4核CPU,由于worker_processes进程数为4,因此上述配置会把每个进程分配一核CPU处理,默认情况下进程不会绑定任何CPU,参数位置为main段。

6、优化nginx事件处理模型-连接数-打开文件配置实战
6.1、nginx事件处理模型
grep events nginx.conf -A 2
在events {
worker_connections 1024;
use epoll; #加入事件处理模型epoll
multi_accept on; #在nginx获得有关新连接的通知后,尝试接受()尽可能多的连接
}
6.2、调整单个进程允许的客户端最大连接数
events {
worker_connections 10240; #修改单个进程允许的客户端最大连接数10240-20480
use epoll;
multi_accept on;
}
6.3、配置每个进程的最大文件打开数
worker_rlimit_nofile 65535;

7、优化服务器名字的hash表大小
如果定义了大量名字,或者定义了非常长的名字,那就需要在http配置模块中调整server_names_hash_max_size,默认512kb,一般是cpu L1的4-5倍,server_names_hash_bucket_size的默认值可能是32,或者是64,或者是其他值,取决于CPU的缓存行的长度。如果这个值是32,那么定义“too.long.server.name.nginx.org”作为虚拟机主机名就会失败,显示如下错误信息:
could not build the server_names_hash,
you should increase server_names_hash_bucket_size;32
出现这种情况,那就需要设置值扩大:
http{
server_names_hash_max_size 512;
server_names_hash_bucket_size 128;
}

8、开启高效文件传输模式
sendfile on;
tcp_nopush on;
#设置连接超时时间,php服务建议短链接,JAVA服务建议长连接
keepalive_timeout 60;
tcp_nodelay on;
client_header_timeout 15;
client_body_timeout 15;
send_timeout 15;
#上传文件大小控制:
client_max_body_size 10m;

9、fastcgi调优(配合php引擎动态服务)
fastcgi_cache_path /tmp/fcgi_cache levels=2:2 keys_zone=fcgi_cache:512m inactive=1d max_size=40g;
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
fastcgi_cache fcgi_cache;
fastcgi_cache_valid 200 302 1h;
fastcgi_cache_valid 301 1d;
fastcgi_cache_valid any 1m;
fastcgi_cache_min_uses 1;

10、配置nginx gzip压缩功能
要压缩的内容:所有程序(大于1K的纯文本文件:js,css,html,xml,shtml)
不要压缩的内容:图片,视频,flash
gzip on;
gzip_min_length 1k;
gzip_buffers 4 32k;
gzip_http_version 1.1;
gzip_comp_level 9;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;
以上内容放在http标签里
火狐浏览器安装firebug,yslow两个组件用来测试nginx的gzip是否配置成功
apache压缩功能实战:
a.开启模块:
LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so
b.httpd.conf中增加

  DeflateCompressionLevel 9
  AddOutputFilterByType DEFLATE text/html text/plain text/xml \

application/json application/xml
  AddOutputFilter DEFLATE js css
  AddOutputFilter INCLUDES .shtml .htm .xml .php .html

c.重启服务器

11、配置nginx expires缓存功能
location ~ .*\.(png|js|css|jpg|gif|xml|svg|ico|html)$ { #由nginx处理静态页面
root html/ROOT;
expires 30d; #使用expires缓存模块,缓存到客户端30天
}

配置apache expires缓存功能:
Apache要设置文件缓存时间,要依靠一个叫mod_expires的模块,但是,我们的机器上,原本是没有安装这个模块的,幸运的是,apache安装这个模块很简单,首先找到源代码。
比如我们的是2.2.22的版本
cd httpd_2.2.22/modules/metadata
sudo /usr/local/apache2/bin/apxs -c -i -a mod_expires.c

这样就完成了mod_expores模块的安装,下面需要修改一下配置文件
sudo vim httpd.conf
在里面加入如下语句
#启用expires_module模块
LoadModule expires_module modules/mod_expires.so

启用有效期控制

ExpiresActive On
#现在只控制swf文件的缓存期为3天
ExpiresByType application/x-shockwave-flash "access plus 3 days"

然后重启apache
sudo ./apachectl restart

mod_expirse这个模块,可以配置如下参数:

ExpiresActive on|off #这个选项表示是否启用有效期控制
ExpiresDefault #用于设置默认的时间
ExpiresByType type/encoding #用于对某一种类型的文件进行控制

有以下几种写法(都表示有效期为1个月):
ExpiresDefault "access plus 1 month"
ExpiresDefault M2592000
设置方法:
1.在apache配置文件httpd.conf中找到
#LoadModule expires_module modules/mod_expires.so 去掉#即可
2.添加配置信息:
ExpiresActive on #缓存十天
ExpiresBytype text/css "access plus 10 days
ExpiresByType application/x-javascript "access plus 10 days "
ExpiresByType image/jpeg "access plus 10 days "
Expiresbytype image/gif "access plus 10 days "

其他设置类似:
LoadModule expires_module modules/mod_expires.so # 启用expires_module模块
ExpiresActive On # 启用有效期控制
ExpiresByType image/gif A2592000 # GIF有效期为1个月
ExpiresByType text/html M604800 # HTML文档的有效期是最后修改时刻后的一星期
#以下的含义类似
ExpiresByType text/css "now plus 2 months"
ExpiresByType text/js "now plus 2 days"
ExpiresByType image/jpeg "access plus 2 months"
ExpiresByType image/bmp "access plus 2 months"
ExpiresByType image/x-icon "access plus 2 months"
ExpiresByType image/png "access plus 2 months"
3.重启apache即可。

12、nginx防爬虫实战及user_agent原理实战
#全局配置
limit_req_zone $anti_spider zone=anti_spider:10m rate=15r/m;
#某个server中
limit_req zone=anti_spider burst=30 nodelay;
if ($http_user_agent ~* "xxspider|xxbot") {
set $anti_spider $http_user_agent;
}
超过设置的限定频率,就会给spider一个503。
上述配置详细解释请自行google下,具体的spider/bot名称请自定义。
nginx中禁止屏蔽网络爬虫:
代码如下:
server {
listen 80;
server_name www.xxx.com;
#charset koi8-r;
#access_log logs/host.access.log main;
#location / {

root html;

    #    index  index.html index.htm;
    #}
    if ($http_user_agent ~* "qihoobot|Baiduspider|Googlebot|Googlebot-Mobile|Googlebot-Image|Mediapartners-Google|Adsbot-Google|Feedfetcher-Google|Yahoo! Slurp|Yahoo! Slurp China|YoudaoBot|Sosospider|Sogou spider|Sogou web spider|MSNBot|ia_archiver|Tomato Bot") 

{
return 403;
}

13、nginx日志相关优化与安全
Nginx日志切割脚本:
#!/bin/sh
#nginx_logs-cut,2015-09-28,linuxzkq
logs_path=/application/nginx/logs
/bin/mv ${logs_path}/access.log ${logspath}/access$(date +%F -d -1day).log
/application/nginx/sbin/nginx -s reload
不记录不需要的访问日志:
对于健康检查或某些图片,js,css的日志,一般不需要记录。
location ~ .*.(png|jpg|gif|ico)$ { #由nginx处理静态页面
access_log off;
}
apache忽略图片访问日志的记录:

SetEnv IMAG 1

CustomLog /var/wwwlogs/b.test.com.log combined env=!IMAG
由于负载均衡的健康检查会造成apache的访问日志被大量写入,使得访问量无法统计,使用下面的方法可以让apache不再记录负载均衡的健康检查日志。
配置(checkstatus.html):
SetEnvIfRequest_URI "^/checkstatus.html" dontlog
ErrorLog logs/error_log
LogLevel warn
CustomLog"logs/access_log" combined env=!dontlog

Nginx访问日志的权限设置
chown -R www.www /app/logs
chmod -R 700 /app/logs
Nginx与apache目录及文件权限设置
为了保证apache与nginx的网站不遭受×××***上传及修改文件
1、所有站点目录的用户和组都不应该为root;
2、所有目录权限是755;
3、所有文件权限是644.
注意:网站服务的用户不能用root!!!!!

14、nginx站点目录及文件URL访问控制
根据扩展名限制程序和文件访问:
location ~ ^/images/..(php|php5)$
{
deny all;
}
location ~ ^/static/.
.(php|php5|sh|pl|py)$
{
deny all;
}
location ~ ^/static/(attachment|avatar)/..(php|php5|sh|bat)$
{
deny all;
}

Nginx限制来源ip访问指定网站目录:
location ~ ^/oldboy/{
deny 192.168.1.1;
allow 202.111.12.211;
allow 10.1.1.0/16;
allow 192.168.1.0/24;
deny all;
}

Nginx限制使用网站IP访问网站:
法一、#禁止IP访问
server {
listen 80 default_server;
servername ;
return 403;
}
法二、也可以把这些流量收集起来,导入到自己的网站,只要做以下跳转设置就可以:
server {
listen 80 default_server;
servername ;
rewrite ^(.*) http://www.mydomain.com permanent;
}

15、http状态码讲解及错误页面优化
http状态码讲解
生产环境常见的HTTP状态码列表(List of HTTP status codes)为:
说明:求精不求多,有舍才有得 不一样的思维不一样的精彩。
200 - OK,服务器成功返回网页

  • Standard response for successful HTTP requests.

301 - Moved Permanently(永久跳转),请求的网页已永久跳转到新位置。

  • This and all future requests should be directed to the given.

403 - Forbidden(禁止访问),服务器拒绝请求

  • forbidden request (matches a deny filter) => HTTP 403
  • The request was a legal request, but the server is refusing to respond to it.

404 - Not Found,服务器找不到请求的页面。

  • The requested resource could not be found but may be available again in the future.

500 - Internal Server Error(内部服务器错误),一般是配置错误

  • internal error in haproxy => HTTP 500
  • A generic error message, given when no more specific message is suitable.

502 - Bad Gateway(坏的网关),一般是网关服务器请求后端服务时,后端服务没有按照http协议正确返回结果。

  • the server returned an invalid or incomplete response => HTTP 502
  • The server was acting as a gateway or proxy and received an invalid response from the upstream server.

503 - Service Unavailable(服务当前不可用),可能因为超载或停机维护。

  • no server was available to handle the request => HTTP 503
  • The server is currently unavailable (because it is overloaded or down for maintenance).

504 - Gateway Timeout(网关超时),一般是网关服务器请求后端服务时,后端服务没有在特定的时间内完成服务。

  • the server failed to reply in time => HTTP 504
  • The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.

16、tmp目录使用内存文件系统作为nginx的proxy_cache
介绍
/dev/shm/是一个使用tmpfs文件系统的设备,其实就是一个特殊的文件系统。redhat中默认大小为物理内存的一半,使用时不用mkfs格式化。
tmpfs是一种基于内存的文件系统,它和虚拟磁盘ramdisk比较类似,但不完全相同,和ramdisk一样,tmpfs可以使用RAM,但它也可以使用swap分区来存储。而且传统的ramdisk是个块设备,要用mkfs来格式化它,才能真正地使用它;而tmpfs是一个文件系统,并不是块设备,只是安装它,就可以使用了。tmpfs是最好的基于RAM的文件系统。
tmpfs是Linux/Unix系统上的一种基于内存的虚拟文件系统。tmpfs可以使用您的内存或swap分区来存储文件(即它的存储空间在virtual memory 中, VM由real memory和swap组成)。由此可见,tmpfs主要存储暂存的文件。它有如下2个优势 :

  1. 动态文件系统的大小。
  2. tmpfs 使用VM建的文件系统,速度当然快。
  3. 重启后数据丢失。

当删除tmpfs中的文件时,tmpfs会动态减少文件系统并释放VM资源,LINUX中可以把一些程序的临时文件放置在tmpfs中,利用tmpfs比硬盘速度快的特点提升系统性能。实际应用中,为应用的特定需求设定此文件系统,可以提升应用读写性能,如将squid 缓存目录放在/tmp, php session 文件放在/tmp, socket文件放在/tmp, 或者使用/tmp作为其它应用的缓存设备
临时修改/dev/shm大小:
#mount -o size=1500M -o nr_inodes=1000000 -o noatime,nodiratime -o remount /dev/shm
mount -t tmpfs -o size=20m tmpfs /tmp 临时挂载使用

开机启用的配置:
可以在/etc/fstab 中定义其大小
tmpfs /dev/shm tmpfs,defaults,size=512m 0 0
tmpfs /tmp tmpfs defaults,size=25M 0 0

修改后执行mount -o remoount /dev/shm 后生效
mkdir /dev/shm/tmp (/dev/shm/ 下新建的目录与/tmp绑定, 则/tmp 即使用tmpfs文件系统)
chmod 1777 /dev/shm/tmp
mount --bind /dev/shm/tmp /tmp

17、禁止资源目录解析php程序
nginx下禁止目录执行php的方法则简单许多,允许设定多个目录
location ~ ^/(attachments|images)/..(php|php5|PHP|PHP5)$
  {
  deny all;
  }
当web目录不是根目录,或者有多个目录的时候可以是
location ~ ^(/discuz/|/bbs/)/(attachments|images)/..(php|php5|PHP|PHP5)$
  {
  deny all;
  }

Apache下禁止目录执行php的方法:

php_flag engine off

lighthttpd下禁止目录执行php的方法:
$HTTP["url"] =~ "^/(forumdata|templates|upload|images)/" {
fastcgi.server = ()
}

18、Nginx的proxy
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 50m; #Nginx上传文件大小限制(动态应用)
client_body_buffer_size 256k;
proxy_connect_timeout 30;
proxy_send_timeout 30;
proxy_read_timeout 60;
proxy_buffer_size 4k;
proxy_buffers 4 32k;
proxy_busy_buffers_size 64k;
proxy_temp_file_write_size 64k;
proxy_next_upstream error timeout invalid_header http_500 http_503 http_404;
proxy_max_temp_file_size 128m;
proxy_store on;
proxy_store_access user:rw group:rw all:r;
#proxy_temp_path /dev/shm/nginx_proxy;
#proxy_temp_path /data2/nginx_cache;

19、Web服务资源防盗链实战
web服务资源防盗链解决办法:
1.图片,视频上打水印,品牌
2.防火墙控制,根据IP控制
3.防盗链(根据referer机制)

apache防盗链实战:
Apache 防盗链的第一种实现方法,可以用 Rewrite 实现。首先要确认 Apache 的 rewrite module 可用:能够控制 Apache httpd.conf 文件的,打开 httpd.conf,确保有这么一行配置:
  LoadModule rewrite_module modules/mod_rewrite.so

  然后在相应虚拟主机配置的地方,加入下列代码:
  ServerName www.php100.com

  # 防盗链配置 参数
  RewriteEngine On
  RewriteCond %{HTTP_REFERER} !^http://php100.com/.$ [NC]
  RewriteCond %{HTTP_REFERER} !^http://php100.com$ [NC]
  RewriteCond %{HTTP_REFERER} !^http://www.php100.com/.
$ [NC]
  RewriteCond %{HTTP_REFERER} !^http://www.php100.com$ [NC]
  RewriteRule .*.(gif|jpg|swf)$ http://www.php100.com/img/nolink.jpg [R,NC]

 1. php100.com/www.php100.com 表示自己的信任站点。gif|jpg|swf 表示要保护文件的扩展名(以|分开)。nolink.jpg盗链后的重定向页面/图片。用以输出警示信息,这张图片应该尽可能的小。

  1. gif|jpg|swf 表示要保护的防止被盗连的文件的扩展名(以|分开)
  2. nolink.jpg 为上述扩展名的资源被盗链后的重定向页面/图片,用以输出警示信息,这张图片应该尽可能的小。
    有些用户使用的是虚拟主机,没有服务器的控制权,无法修改 httpd.conf 文件和重启服务器。那么请确认你的虚拟主机支持 .htaccess,将上面的配置写入 .htaccess 文件,放入根目录或图片所在的目录即可:

  # 防盗链配置
  RewriteEngine On
  RewriteCond %{HTTP_REFERER} !^http://php100.com/.$ [NC]
  RewriteCond %{HTTP_REFERER} !^http://php100.com$ [NC]
  RewriteCond %{HTTP_REFERER} !^http://www.php100.com/.
$ [NC]
  RewriteCond %{HTTP_REFERER} !^http://www.php100.com$ [NC]
  RewriteRule .*.(gif|jpg|swf)$ http://www.php100.com/img/nolink.jpg [R,NC]

   通过判断referer变量的值,判断图片或资源的引用是否合法,只有在设定范围内的 referer,才能访问指定的资源,从而实现了防盗链(Anti-Leech)的目的。需要指出的是:不是所有的用户代理(浏览器)都会设置 referer 变量,而且有的还可以手工修改 referer,也就是说,referer 是可以被伪造的。本文所讲的,只是一种简单的防护手段。当然,应付一般的盗链也足够了。

Nginx防盗链实战:
如果您使用的是默认站点,也就是说,您的站点可以直接输入服务器IP访问的,使用root登录,修改 /usr/local/nginx/conf/nginx.conf 这个配置文件。

如果您新建了站点,那么修改/usr/local/nginx/conf/vhost/你的域名.conf 这个配置文件,找到:
location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}

把这一段删掉,修改成:
location ~ .(gif|jpg|png|jpeg)$ {
expires 30d;
valid_referers none blocked
.hugao8.com www.hugao8.com m.hugao8.com .baidu.com .google.com;
if ($invalid_referer) {
rewrite ^/ http://ww4.sinaimg.cn/bmiddle/051bbed1gw1egjc4xl7srj20cm08aaa6.jpg;
#return 404;
}
}

第一行: location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$

其中“gif|jpg|jpeg|png|bmp|swf”设置防盗链文件类型,自行修改,每个后缀用“|”符号分开!

第三行:valid_referers none blocked *.it300.com it300.com;

就是白名单,允许文件链出的域名白名单,自行修改成您的域名!*.it300.com这个指的是子域名,域名与域名之间使用空格隔开!

第五行:rewrite ^/ http://www.it300.com/static/images/404.jpg;

这个图片是盗链返回的图片,也就是替换盗链网站所有盗链的图片。这个图片要放在没有设置防盗链的网站上,因为防盗链的作用,这个图片如果也放在防盗链网站上就会被当作防盗链显示不出来了,盗链者的网站所盗链图片会显示X符号。

这样设置差不多就可以起到防盗链作用了,上面说了,这样并不是彻底地实现真正意义上的防盗链!

我们来看第三行:valid_referers none blocked *.it300.com it300.com;
valid_referers 里多了“none blocked”

我们把“none blocked”删掉,改成
valid_referers *.it300.com it300.com;

nginx彻底地实现真正意义上的防盗链完整的代码应该是这样的:
location ~ .(gif|jpg|png|jpeg)$ {
expires 30d;
valid_referers
.hugao8.com www.hugao8.com m.hugao8.com .baidu.com .google.com;
if ($invalid_referer) {
rewrite ^/ http://ww4.sinaimg.cn/bmiddle/051bbed1gw1egjc4xl7srj20cm08aaa6.jpg;
#return 404;
}
}

这样您在浏览器直接输入图片地址就不会再显示图片出来了,也不可能会再右键另存什么的。

第五行:rewrite ^/ http://www.it300.com/static/images/404.jpg;

这个是给图片防盗链设置的防盗链返回图片,如果我们是文件需要防盗链下载,把第五行:
rewrite ^/ http://www.it300.com/static/images/404.jpg;

改成一个链接,可以是您主站的链接,比如把第五行改成:
rewrite ^/ http://www.it300.com;

这样,当别人输入文件下载地址,由于防盗链下载的作用就会跳转到您设置的这个链接!
最后,配置文件设置完成别忘记重启nginx生效!

20、Nginx伪静态的配置解决方案实战
Nginx Web Server:
rewrite ^([^.])/topic-(.+).html$ $1/portal.php?mod=topic&topic=$2 last;
rewrite ^([^.]
)/article-([0-9]+)-([0-9]+).html$ $1/portal.php?mod=view&aid=$2&page=$3 last;
rewrite ^([^.])/forum-(\w+)-([0-9]+).html$ $1/forum.php?mod=forumdisplay&fid=$2&page=$3 last;
rewrite ^([^.]
)/thread-([0-9]+)-([0-9]+)-([0-9]+).html$ $1/forum.php?mod=viewthread&tid=$2&extra=page%3D$4&page=$3 last;
rewrite ^([^.])/group-([0-9]+)-([0-9]+).html$ $1/forum.php?mod=group&fid=$2&page=$3 last;
rewrite ^([^.]
)/space-(username|uid)-(.+).html$ $1/home.php?mod=space&$2=$3 last;
rewrite ^([^.])/blog-([0-9]+)-([0-9]+).html$ $1/home.php?mod=space&uid=$2&do=blog&id=$3 last;
rewrite ^([^.]
)/(fid|tid)-([0-9]+).html$ $1/index.php?action=$2&value=$3 last;
rewrite ^([^.])/([a-z]+[a-z0-9_])-([a-z0-9_-]+).html$ $1/plugin.php?id=$2:$3 last;
if (! -e $request_filename) {
return 404;
}

DISCUZ伪静态及防盗链案例:
server {
listen 80;
servername bbs.etiantian.org;
index index.php index.html index.htm;
root /application/data/bbs;
rewrite ^([^.])/topic-(.+).html$ $1/portal.php?mod=topic&topic=$2 last;
rewrite ^([^.]
)/article-([0-9]+)-([0-9]+).html$ $1/portal.php?mod=view&aid=$2&page=$3 last;
rewrite ^([^.])/forum-(\w+)-([0-9]+).html$ $1/forum.php?mod=forumdisplay&fid=$2&page=$3 last;
rewrite ^([^.]
)/thread-([0-9]+)-([0-9]+)-([0-9]+).html$ $1/forum.php?mod=viewthread&tid=$2&extra=page%3
D$4&page=$3 last;
rewrite ^([^.])/group-([0-9]+)-([0-9]+).html$ $1/forum.php?mod=group&fid=$2&page=$3 last;
rewrite ^([^.]
)/space-(username|uid)-(.+).html$ $1/home.php?mod=space&$2=$3 last;
rewrite ^([^.])/blog-([0-9]+)-([0-9]+).html$ $1/home.php?mod=space&uid=$2&do=blog&id=$3 last;
rewrite ^([^.]
)/(fid|tid)-([0-9]+).html$ $1/index.php?action=$2&value=$3 last;
rewrite ^([^.]*)/([a-z]+[a-z0-9
])-([a-z0-9_-]+).html$ $1/plugin.php?id=$2:$3 last;
if (! -e $request_filename) {
return 404;
}
location ~
.(gif|jpg|png|jpeg)$ {
valid_referers bbs.etiantian.org;
if ($invalid_referer) {
#return 403;
rewrite ^/ http://bbs.etiantian.org/daolian.html;
}
}
location ~* .(php|php5)$ {
fastcgi_index index.php;
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
include fastcgi_params;
}
}

21、Nginx优化之针对错误页面进行优雅显示
error_page 403 /403.html;
error_page 404 /404.html;
error_page 400 http://oldboy.blog.51cto.com;
#error_page 404 /404.html;
#redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}

22、Nginx优化之控制单IP并发连接与连接速率控制防DOS
1、http {
limit_conn_zone $binary_remote_addr zone=addr:10m;
...
server {
...
location /download/ {
limit_conn addr 1;
}

limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
location /download/ {
limit_conn addr 1;
}

limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;
server {
...
limit_conn perip 10;
limit_conn perserver 100;
}

2、http {
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
...
server {
...
location /search/ {
limit_req zone=one burst=5;
}

23、Nginx优化之磁盘挂载优化以及Linux内核优化
磁盘挂载优化:
LABEL=/nginx /nginx ext3 defaults,nosuid,noexec,nodev 1

完整的Linux内核优化配置:
net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rmem = 4096 87380 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 262144
net.core.somaxconn = 262144
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_fin_timeout = 1
net.ipv4.tcp_keepalive_time = 30
net.ipv4.ip_local_port_range = 1024 65000

24、Nginx优化-为特殊Web服务增加用户身份验证
$ htpasswd -cb /application/nginx/conf/htpasswd oldboy 123456
Adding password for user oldboy
$ chmod 400 /application/nginx/conf/htpasswd

server {
listen 80;
server_name localhost;
charset utf8;
location / {
root /application/data/phpMyAdmin;
index index.php index.html index.htm;
auth_basic "oldboy training";
auth_basic_user_file /application/nginx/conf/htpasswd;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
location ~ .(php|php5)?$ {
root /application/data/phpMyAdmin;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}

25、让Nginx服务以及Nginx站点运行于监牢模式下
架构师提供的解决方案
使用普通用户启动Nginx(监牢模式):
1.给nginx服务降权,使用ynca用户跑服务,站点也是ynca权限,给开发设置普通账号和ynca同组。
2.开发重启nginx,管理站点程序,查看日志。项目负责制:责任你来负责。
参考资料:http://down.51cto.com/data/844517
[root@LNMP-07 conf]# useradd ynca
[root@LNMP-07 conf]# ll /home
total 8
drwx------ 2 ynca ynca 4096 Oct 27 00:54 ynca
[root@LNMP-07 conf]# mkdir /home/ynca/www
[root@LNMP-07 conf]# /application/nginx/sbin/nginx -h
nginx version: nginx/1.8.0
Usage: nginx [-?hvVtq] [-s signal] [-c filename] [-p prefix] [-g directives]

Options:
-?,-h : this help
-v : show version and exit
-V : show version and configure options then exit
-t : test configuration and exit
-q : suppress non-error messages during configuration testing
-s signal : send signal to a master process: stop, quit, reopen, reload
-p prefix : set prefix path (default: /application/nginx-1.8.0/)
-c filename : set configuration file (default: conf/nginx.conf)
-g directives : set global directives out of configuration file
[root@LNMP-07 conf]# cp nginx.conf /home/ynca/
[root@LNMP-07 conf]# cd /home/ynca/
[root@LNMP-07 ynca]# ll
total 12
-rw-r--r-- 1 root root 5439 Oct 27 01:15 nginx.conf
drwxr-xr-x 2 root root 4096 Oct 27 00:55 www
[root@LNMP-07 ynca]# mkdir conf
[root@LNMP-07 ynca]# mv nginx.conf conf/
[root@LNMP-07 ynca]# ll
total 8
drwxr-xr-x 2 root root 4096 Oct 27 01:16 conf
drwxr-xr-x 2 root root 4096 Oct 27 00:55 www
[root@LNMP-07 ynca]# pwd
/home/ynca
[root@LNMP-07 ynca]# mkdir log
[root@LNMP-07 ynca]# ll
total 12
drwxr-xr-x 2 root root 4096 Oct 27 01:16 conf
drwxr-xr-x 2 root root 4096 Oct 27 01:17 log
drwxr-xr-x 2 root root 4096 Oct 27 00:55 www
[root@LNMP-07 ynca]# chown -R ynca.ynca
[root@LNMP-07 ynca]# ll
total 12
drwxr-xr-x 2 ynca ynca 4096 Oct 27 01:16 conf
drwxr-xr-x 2 ynca ynca 4096 Oct 27 01:17 log
drwxr-xr-x 2 ynca ynca 4096 Oct 27 00:55 www
[root@LNMP-07 ynca]# killall nginx
[root@LNMP-07 ynca]# lsof -i:80
[root@LNMP-07 ynca]# /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
nginx: [emerg] open() "/home/ynca/conf/mime.types" failed (2: No such file or directory) in /home/ynca/conf/nginx.
[root@LNMP-07 ynca]# ln -s /application/nginx/conf/mime.types /home/ynca/conf/mime.types
[root@LNMP-07 ynca]# /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
nginx: [emerg] open() "/home/ynca/conf/fastcgi_params" failed (2: No such file or directory) in /home/ynca/conf/nginx.conf:71
[root@LNMP-07 ynca]# ln -s /application/nginx/conf/fastcgi_params /home/ynca/conf/fastcgi_params
[root@LNMP-07 ynca]# /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
nginx: [emerg] unexpected end of file, expecting "}" in /home/ynca/conf/nginx.conf:75 #配置文件上面少一个大括号
[root@LNMP-07 ynca]# /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
[root@LNMP-07 ynca]# ps -ef|grep nginx|grep -v grep
root 1548 1 0 01:39 ? 00:00:00 nginx: master process /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
ynca 1549 1548 0 01:39 ? 00:00:00 nginx: worker process
[root@LNMP-07 conf]# su - ynca
[ynca@LNMP-07 ~]$ /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
nginx: [alert] could not open error log file: open() "/application/nginx-1.8.0/logs/error.log" failed (13: Permission denied)
2015/10/27 01:51:29 [warn] 1637#0: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /home/ynca/conf/nginx.conf:2
2015/10/27 01:51:29 [emerg] 1637#0: open() "/home/ynca/log/access_log" failed (13: Permission denied)
[ynca@LNMP-07 ~]$ ll
total 12
drwxr-xr-x 2 ynca ynca 4096 Oct 27 01:47 conf
drwxr-xr-x 2 ynca ynca 4096 Oct 27 01:39 log
drwxr-xr-x 2 ynca ynca 4096 Oct 27 00:55 www
[root@LNMP-07 ynca]# chown -R ynca.ynca

[ynca@LNMP-07 ~]$ /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
nginx: [alert] could not open error log file: open() "/application/nginx-1.8.0/logs/error.log" failed (13: Permission denied)
2015/10/27 02:00:32 [warn] 1729#0: the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /home/ynca/conf/nginx.conf:2
nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied)
[root@LNMP-07 ynca]# cd /application/nginx/logs
[root@LNMP-07 logs]# ls
access.log access_2015-10-12.log
access_2015-09-27.log access_2015-10-16.log
access_2015-09-28.log access_2015-10-17.log
access_2015-09-29.log access_2015-10-19.log
access_2015-09-30.log access_2015-10-21.log
access_2015-10-02.log access_2015-10-23.log
access_2015-10-05.log access_2015-10-26.log
access_2015-10-06.log error.log
access_2015-10-09.log
[root@LNMP-07 logs]# chown -R ynca.ynca error.log
[ynca@LNMP-07 ~]$ /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
nginx: [warn] the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /home/ynca/conf/nginx.conf:2
nginx: [emerg] open() "/application/nginx-1.8.0/logs/nginx.pid" failed (13: Permission denied)
[root@LNMP-07 ynca]# vi conf/nginx.conf
user ynca ynca;
worker_processes 1;
error_log /home/ynca/log/error_log;
pid /home/ynca/log/nginx.pid;
[ynca@LNMP-07 ~]$ lsof -i:80
[ynca@LNMP-07 ~]$ /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
nginx: [warn] the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /home/ynca/conf/nginx.conf:2
[ynca@LNMP-07 ~]$ ps -ef|grep nginx|grep -v grep
ynca 1765 1 0 02:14 ? 00:00:00 nginx: master process /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
ynca 1766 1765 0 02:14 ? 00:00:00 nginx: worker process
[ynca@LNMP-07 ~]$ grep -Ev "#|^$" conf/nginx.conf
user ynca ynca;
worker_processes 1;
error_log /home/ynca/log/error_log;
pid /home/ynca/log/nginx.pid;
events {
worker_connections 1024;
}
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"';
sendfile on;
tcp_nopush on;
keepalive_timeout 60;
server_tokens off;
gzip on;
gzip_min_length 1k;
gzip_buffers 4 32k;
gzip_http_version 1.1;
gzip_comp_level 9;
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;

server {
    listen       8080;
    server_name  www.etiantian.com;
    location / {
        root   /home/ynca/www;
        index  index.php index.html index.htm;
    }
    location ~ \.php$ {
        root           /home/ynca/www;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
     access_log    /home/ynca/log/access_log; 
 }

}
[ynca@LNMP-07 www]$ curl -i localhost:8080
HTTP/1.1 200 OK
Server: nginx
Date: Mon, 26 Oct 2015 18:27:25 GMT
Content-Type: text/html
Content-Length: 23
Last-Modified: Mon, 26 Oct 2015 18:24:43 GMT
Connection: keep-alive
ETag: "562e6feb-17"
Accept-Ranges: bytes

监牢模式_linuxzkq
[ynca@LNMP-07 www]$ killall nginx
[ynca@LNMP-07 www]$ ps -ef|grep nginx|grep -v grep
[ynca@LNMP-07 www]$ /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
nginx: [warn] the "user" directive makes sense only if the master process runs with super-user privileges, ignored in /home/ynca/conf/nginx.conf:2
[ynca@LNMP-07 www]$ /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf &>/dev/null
[ynca@LNMP-07 www]$ ps -ef|grep nginx|grep -v grep
ynca 1797 1 0 02:29 ? 00:00:00 nginx: master process /application/nginx/sbin/nginx -c /home/ynca/conf/nginx.conf
ynca 1798 1797 0 02:29 ? 00:00:00 nginx: worker process

26、php引擎php.ini参数优化实战
无论是apache还是nginx,php.ini都是适合的;而php-fpm.conf适合nginx+fcgi的配置。
php.ini配置文件:
[PHP]
engine = On
short_open_tag = Off
asp_tags = Off
precision = 14
output_buffering = 4096
zlib.output_compression = Off
implicit_flush = Off
unserialize_callback_func =
serialize_precision = 17
disable_functions = #关闭危险函数,在等号后面写上要禁用的危险函数
disable_classes =
zend.enable_gc = On
expose_php = On #关闭php版本信息,修改为Off。
max_execution_time = 30 #设置每个脚本运行的最长时间
max_input_time = 60 #每个脚本等待输入数据的最长时间
memory_limit = 128M #设置每个脚本使用的最大内存
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
display_errors = Off #错误信息控制,建议设置为:Off
display_startup_errors = Off
log_errors = On #错误日志,建议打开
error_log = /application/logs/php_errors.log #添加错误日志路径
log_errors_max_len = 1024
ignore_repeated_errors = Off
ignore_repeated_source = Off
report_memleaks = On
track_errors = Off
html_errors = On
variables_order = "GPCS"
request_order = "GP"
register_argc_argv = Off
auto_globals_jit = On
post_max_size = 8M
auto_prepend_file =
auto_append_file =
default_mimetype = "text/html"
default_charset = "UTF-8"
doc_root =
user_dir =
extension_dir = "/application/php5.6.12/lib/php/extensions/no-debug-zts-20131226/"
enable_dl = Off
file_uploads = On
upload_max_filesize = 2M #上传文件的最大许可大小
max_file_uploads = 20
allow_url_fopen = On #禁止打开远程地址,建议设置为Off
allow_url_include = Off
default_socket_timeout = 60
cgi.fix_pathinfo = 0 #防止Nginx文件类型错误解析漏洞
session_save_handler = files #php_session信息存放类型:memcache
session_save_path = "/tmp" #php_session信息存放位置:tcp://10.0.0.18:11211
[CLI Server]
cli_server.color = On
[Pdo_mysql]
pdo_mysql.cache_size = 2000
pdo_mysql.default_socket=
[Phar]
[mail function]
SMTP = localhost
smtp_port = 25
mail.add_x_header = On
[SQL]
sql.safe_mode = Off # safe_mode = Off #修改为on,启用安全模式 safe_mode_gid = Off #用户组安全
[ODBC]
odbc.allow_persistent = On
odbc.check_persistent = On
odbc.max_persistent = -1
odbc.max_links = -1
odbc.defaultlrl = 4096
odbc.defaultbinmode = 1
[Interbase]
ibase.allow_persistent = 1
ibase.max_persistent = -1
ibase.max_links = -1
ibase.timestampformat = "%Y-%m-%d %H:%M:%S"
ibase.dateformat = "%Y-%m-%d"
ibase.timeformat = "%H:%M:%S"
[MySQL]
mysql.allow_local_infile = On
mysql.allow_persistent = On
mysql.cache_size = 2000
mysql.max_persistent = -1
mysql.max_links = -1
mysql.default_port =
mysql.default_socket =
mysql.default_host =
mysql.default_user =
mysql.default_password =
mysql.connect_timeout = 60
mysql.trace_mode = Off
[MySQLi]
mysqli.max_persistent = -1
mysqli.allow_persistent = On
mysqli.max_links = -1
mysqli.cache_size = 2000
mysqli.default_port = 3306
mysqli.default_socket =
mysqli.default_host =
mysqli.default_user =
mysqli.default_pw =
mysqli.reconnect = Off
[mysqlnd]
mysqlnd.collect_statistics = On
mysqlnd.collect_memory_statistics = Off
[PostgreSQL]
pgsql.allow_persistent = On
pgsql.auto_reset_persistent = Off
pgsql.max_persistent = -1
pgsql.max_links = -1
pgsql.ignore_notice = 0
pgsql.log_notice = 0
[Sybase-CT]
sybct.allow_persistent = On
sybct.max_persistent = -1
sybct.max_links = -1
sybct.min_server_severity = 10
sybct.min_client_severity = 10
[bcmath]
bcmath.scale = 0
[Session]
session.save_handler = files
session.use_strict_mode = 0
session.use_cookies = 1
session.use_only_cookies = 1
session.name = PHPSESSID
session.auto_start = 0
session.cookie_lifetime = 0
session.cookie_path = /
session.cookie_domain =
session.cookie_httponly =
session.serialize_handler = php
session.gc_probability = 1
session.gc_divisor = 1000
session.gc_maxlifetime = 1440
session.referer_check =
session.cache_limiter = nocache
session.cache_expire = 180
session.use_trans_sid = 0
session.hash_function = 0
session.hash_bits_per_character = 5
url_rewriter.tags = "a=href,area=href,frame=src,input=src,form=fakeentry"
[Tidy]
tidy.clean_output = Off
[soap]
soap.wsdl_cache_enabled=1
soap.wsdl_cache_dir="/tmp"
soap.wsdl_cache_ttl=86400
soap.wsdl_cache_limit = 5
[ldap]
ldap.max_links = -1
[opcache]
extension = imagick.so
extension = memcache.so
zend_extension = opcache.so
extension = pdo_mysql.so
[xcache-common]
extension = xcache.so
[xcache.admin]
xcache.admin.enable_auth = On
xcache.admin.user = "mOo"
xcache.admin.pass = "md5 encrypted password"
[xcache]
xcache.shm_scheme = "mmap"
xcache.size = 128M
xcache.count = 2
xcache.slots = 8K
xcache.ttl = 86400
xcache.gc_interval = 3600
xcache.var_size = 4M
xcache.var_count = 1
xcache.var_slots = 8K
xcache.var_ttl = 0
xcache.var_maxttl = 0
xcache.var_gc_interval = 300
xcache.var_namespace_mode = 0
xcache.var_namespace = ""
xcache.readonly_protection = Off
xcache.mmap_path = "/dev/zero"
xcache.coredump_directory = ""
xcache.coredump_type = 0
xcache.disable_on_crash = Off
xcache.experimental = Off
xcache.cacher = On
xcache.stat = On
xcache.optimizer = Off
[xcache.coverager]
xcache.coverager = Off
xcache.coverager_autostart = On
xcache.coveragedump_directory = ""
register_globals = Off #关闭注册全局变量,建议设置为Off
magic_quotes_gpc = Off #打开此选项,防止SQL注入,修改为:On

FastCGI优化(php-fpm):
CGI全称是“公共网关接口”(Common Gateway Interface),HTTP服务器与你的或其它机器上的程序进行“交谈”的一种工具,其程序一般运行在网络服务器上。 CGI可以用任何一种语言编写,只要这种语言具有标准输入、输出和环境变量。如php,perl,tcl等。
php-fpm.conf参数优化实战(基于php-5.3.27优化):
25 ;pid = run/php-fpm.pid #pid = /app/logs/php-fpm.pid
32 ;error_log = log/php-fpm.log #error_log = /app/logs/php-fpm.log
50 ;log_level = notice #log_level = error
108 ;events.mechanism = epoll #events.mechanism = epoll
175 ;listen.owner = nginx #listen.owner = nginx
176 ;listen.group = nginx #listen.group = nginx
235 pm.max_children = 5 #建议修改为:1024
240 pm.start_servers = 2 #建议修改为:16
245 pm.min_spare_servers = 1 #建议修改为:5
250 pm.max_spare_servers = 3 #建议修改为:20
255 ;pm.process_idle_timeout = 10s; #建议修改为:pm.process_idle_timeout = 15s
261 ;pm.max_requests = 500 #建议修改为:pm.max_requests = 2048
441 ;slowlog = log/$pool.log.slow #取消注释"分号",slowlog = /app/logs/$pool.log.slow
447 ;request_slowlog_timeout = 0 #修改为request_slowlog_timeout = 10
458 ;rlimit_files = 1024 #修改为rlimit_files = 32768