Nginx相对于Apache优点:
高并发响应性能非常好,官方Nginx处理静态文件并发5w/s
反向代理性能非常好。(可用于负载均衡)
内存和cpu占用率低。(为Apache的1/5-1/10)
功能较Apache少(常用功能均有)
对php可使用cgi方式和fastcgi方式。
Nginx WEB安装
实验机器:192.168.244.128
首先需要安装pcre库,然后再安装Nginx:
安装pcre支持rewrite库,也可以安装源码,注*安装源码时,指定pcre路径为解压
源码的路径,而不是编译后的路径,否则会报错
(make[1]: *** [/usr/local/pcre/Makefile] Error 127 错误)
yum install pcre-devel pcre -y
#下载Nginx源码包
root@192.168.244.128 ~]# wget http://nginx.org/download/nginx-1.6.3.tar.gz
#进入解压目录,然后sed修改Nginx版本信息为WS(防止版本信息被恶意者查到)
cd nginx-1.6.3 ; sed -i -e ‘s/1.6.3//g’ -e ‘s/nginx//WS/g’ -e
‘s/“NGINX”/“WS”/g’ src/core/nginx.h
#预编译Nginx
./configure --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
#.configure预编译成功后,执行make命令进行编译
make
#make执行成功后,执行make install 正式安装
make install
#自此Nginx安装完毕
/usr/local/nginx/sbin/nginx -t 检查nginx配置文件是否正确,返回OK即正确。
[root@192.168.244.128~]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful#启动nginx ,你也可以写一个服务启动脚本
root@192.168.244.128 ~]# /usr/local/nginx/sbin/nginx
[root@192.168.244.128 ~]# ps -ef | grep nginx
root 21715 1 0 14:01 ? 00:00:00 nginx: master process /usr/local/nginx/sbin/nginx
nobody 21716 21715 0 14:01 ? 00:00:00 nginx: worker process
root 21718 20717 0 14:01 pts/2 00:00:00 grep nginx
配置nginx启动脚本
cd /etc/nginx/init.d/ #cd到/etc/init.d目录下 启动脚本
chmod +x /etc/init.d/nginx #设置可执行权限 我把自己yq用户设置好权限以后不用root就可以改
chkconfig --add nginx #将nginx添加为系统的服务
chkconfig --list nginx #查看nginx的开机运行级别
vim init.d
nginx=/usr/local/nginx/sbin/nginx
case $1 in
start)
netstat -anlpt | grep nginx
if [ $? -eq 0 ]
then
echo "nginx-server isalready running"
else
echo "nginx-server beginstart"
$nginx
fi
;;
stop)
$nginx -s stop
if [ $? -eq 0 ]
then
echo "nginx-server isstoped"
else
echo "nginx-server stopfail,try again"
fi
;;
status)
netstat -anlpt | grep nginx
if [ $? -eq 0 ]
then
echo "nginx-server isrunning"
else
echo "nginx-server isstoped"
fi
;;
restart)
$nginx -s reload &>/dev/null
if [ $? -eq 0 ]
then
echo "nginx-server isbegin restart"
else
echo "nginx-server restartfail"
fi
;;
*)
echo "please enter {startrestart status stop}"
;;
esac
exit 0
# shell脚本基本语法,你可以了解下,反正copy一下 然后 source.nginx重置配置
/usr/local/nginx/sbin/nginx -s stop 停止服务
[root@192.168.244.128 ~]# /usr/local/nginx/sbin/nginx -v 查看版本
nginx version: WS
[root@192.168.244.128~]# /usr/local/nginx/sbin/nginx -V 查看编译参数
nginx version: WS
built by gcc 4.4.7 20120313 (Red Hat 4.4.7-11) (GCC)
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
然后就可一在客户端访问可以查看到测试页面如下:
nginx.conf 我自己找的综合起来的配置
#user nobody; 配置用户 如user test test;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
error_log /usr/local/nginx/logs/error.log debug;
#pid logs/nginx.pid;
events {
accept_mutex on; #设置网路连接序列化,防止惊群现象发生,默认为on
multi_accept on; #设置一个进程是否同时接受多个网络连接,默认为off
#use epoll; #nginx官方建议,可以不指定事件处理模型,Nginx会自动选择最佳的事,select|poll|kqueue|epoll|resig|/dev/poll|eventport
worker_connections 1024; #最大连接数,默认为512
}
http {
include mime.types; #文件扩展名与文件类型映射表
default_type application/octet-stream; #默认文件类型,默认为text/plain
#access_log off; #取消服务日志
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 logs/access.log main; #combined为日志格式的默认值
server_names_hash_bucket_size 128;
client_header_buffer_size 32k;
large_client_header_buffers 4 32k;
client_max_body_size 10m; #上传文件大小设置,具体数字要根据业务需求动态决定
sendfile on; #允许sendfile方式传输文件,默认为off,可以在http块,server块,location块。
sendfile_max_chunk 100k; #每个进程每次调用传输数量不能大于设定的值,默认为0,即不设上限。
tcp_nopush on;
#tcp_nopush on;增加缓冲区的方法,彻底解决了Nginx 502 Bad Gateway的问题
tcp_nodelay on;
fastcgi_connect_timeout 300; #php相关配置,缓存更好的解决网络延时,访问量大的问题
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;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
gzip on; #压缩功能
gzip_min_length 1k; #允许压缩的最小页面字节数
gzip_buffers 4 16k; #压缩缓冲大小
gzip_http_version 1.0; #压缩版本,默认为1.0
gzip_comp_level 2; #压缩比例
gzip_types text/plain application/x-javascript text/css application/xml; #指定压缩的内容类型
gzip_vary on; #vary header支持,让前端的缓存服务器继续缓存传输该压缩页面
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ #指定缓存文件的类型 配置Nginx expires缓存功能;expires缓存的缺点就是在网站更新相关数据后,用户如果不清理缓存看到的就会一直是过期的数据,为了解决这个问题,可以1、缩短缓存时间,比如百度的首页图片缓存时间为一天;2、服务后台更改图片名称,这样就相当于是一个新的页面内容,用户会重新下载 3、相关的CSS、JS推送到CDN
{
expires 3650d; #指定缓存时间
}
location ~ .*\.(js|css)?$
{
expires 3d;
}
upstream mysvr {
server 127.0.0.1:7878; #部署Tomcat时候代理配置
server 192.168.240.128:3333 backup; #热备
}
#Nginx访问控制
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location ~*^.+$ { #Nginx防盗链 :请求的url过滤,正则匹配,~为区分大小写,~*为不区分大小写
root html;
index index.html index.htm;
#proxy_pass http://mysvr; #请求转向mysvr 定义的服务器列表
#deny 127.0.0.1; #拒绝的ip
allow 192.168.240.128; #允许的ip
deny all;
}
#匹配以php结尾的文件
location ~ .*\.(php|php5)?${
root html/php;
include fastcgi_params;
fastcgi_pass unix:/tmp/php-fcgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/local/nginx/js$fastcgi_script_name; #这里的路径要和root路径一致
}
}
#error_page 404 /404.html; Nginx错误页面的优雅显示
# redirect server error pages to the static page /50x.html
#
#error_page 500 502 503 504 /50x.html;
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
进程查询命令
ps -ef|grep nginx|grep -v grep
Nginx日志相关优化与安全
1)每天进行日志切割,备份
#!/bin/sh
cd /application/nginx/logs/
mv www_access.log www.access_$(date +%F -d -1day).log
mv blog_access.log blog.access_$(date +%F -d -1day).log
/application/nginx/sbin/nginx -s reload
cat >>/var/spool/cron/root<<EOF
00 00 * * * /bin/sh /server/scripts/cut_nginx_log.sh >/dev/null 2>&1
EOF
2)不记录不需要的访问日志
location ~ .*\.(js|jpg|JPG|jpeg|JPEG|css|bmp|gif|GIF)$ {
access_log off;
}
3)访问日志的权限设置
chown -R root.test/application/nginx/logs或者
chmod -R 700 /application/logs
Nginx防爬虫优化
robots.txt机器人协议
网络爬虫排除标准,告诉搜索引擎哪些目录可以抓取,哪些禁止抓取
禁止下载协议代理
if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
return 403;
}
防止N多爬虫代理访问网站
if ($http_user_agent ~*
“qihoobot|Baiduspider|Googlebot|Googlebot-Mobile|Googlebot-Image|Mediapartners-Google|Adsbot-Google|Yahoo! Slurp China|YoudaoBot|Sosospider|Sogou spider|Sogou web spider|MSNBot”) {
return 403;
}
禁止不同浏览器访问
if ($http_user_agent ~* “Firefox|MSIE”)
{
rewrite ^(.*) http://blog.etiantian.org/$1 permanent
}
限制HTTP请求方法
if ($request_method !~ ^(GET|HEAD|POST)$ ) {
return 501;
}
只允许GET等,允许DELETE、SEARCH等
为防止黑客通过上传服务器执行木马,也可以在上传服务器上做限制HTTP的GET
if ($request_method ~* ^(GET)$ ) {
return 501;
}
防DOS
使用limit_conn_zone进行控制,控制单个IP或域名的访问次数,限制连续访问
limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_remote_addr zone=perserver:10m;
server {
limit_conn perip 10;
limit_conn perserver 100;
}
#还可以使用limit_req_zone进行控制,控制单个IP的访问速率
使用CDN为网站内容加速
全国或全球的内容分布式缓存集群,其实质通过智能DNS判断用户的来源地域及上网线路,为用户选择一个最接近用户地域,以及和用户上网线路相同的服务器节点,提升用户浏览网站的体验
要加速的业务数据应该存在独立的域名,然后删除A记录解析,使用CNAME解析
Nginx程序架构优化
解耦,一堆程序代码按照业务用途分开,然后提供服务,例如:注册登录、上传、下载、浏览列表、商品内容、订单支付等都应该是独立的程序服务,只不过在客户端看来是一个整体而已,小公司最起码要做到的解耦是
- 网页页面服务
- 图片附件及下载服务上传图片服务
- 使用普通用户启动Nginx(监牢模式)
降权思想,Nginx的Master进程使用的是root用户,worker进程使用的是nginx指定的普通用户,用root跑nginx的Master进程有两大问题:1是最小化权限分配遇到问题;2、网站一旦有漏洞,很容易丢掉root权限
降权执行的好处:
1、创建普通用户inca,用inca跑Nginx服务,开发运维都使用普通帐号,只要和inca同组,照样可以管理nginx,还解决了root权限太大问题
2、职责分明,相关账号负责维护程序和日志,出问题负首要责