什么是Nginx?
Nginx的特性
Nginx的优点
Nginx转发规则配置
include /usr/local/nginx/conf/vhost/*.conf;
~mkdirconf/vhost
~vim conf/vhost/tomcat_dangdang.conf
server {
listen 80;
server_namewww.dangdang.cn;
location / {
proxy_pass http://tomcat_dangdang;
}
}
upstream tomcat_dangdang {
server 10.10.100.10:8080;
}
Nginx静态文件转发规则
location ^~ /static/activity/ {
alias /static/activity/;
}
location ^~ /static/activity/ {
root / ;
}
区别:
alias后面必须要用“/”结束,否则会找不到文件的,而root则可有可无
例如访问路径为www.dangdang.cn/static/activity/img
而alias和root配置相同时,root的转发会访问 /static/activity/static/activity/img/
Nginx转发规则顺序
负载均衡
upstream bbs_server_pool {
server 192.168.1.15:80 weight=1max_fails=2fail_timeout=30s;
server 192.168.1.16:80 weight=1max_fails=2fail_timeout=30s;
server 192.168.1.17:80 weight=1max_fails=2fail_timeout=30s;
server 192.168.1.18:80 weight=1max_fails=2fail_timeout=30s;
}
❖weight越高权重越高,max_fails指定重试次数,fail_timeout是超时时间
访问控制
location /docs/ {
## 禁止192.168.1.1ip访问
deny 192.168.1.1;
##允许 192.168.1.0/24段ip访问
allow 192.168.1.0/24;
## 允许10.10.100.0/16段ip访问
allow 10.10.100.0/16;
## drop禁止所有ip访问
deny all;
}
从上到下的顺序。匹配到了便跳出。如上的例子先禁止了192.16.1.1,接下来允许了2个网段,最后未匹配的IP全部禁止访问.缓存配置
location ^~ /static/activity/ {
alias /static/activity/;
expires 3d;
#expires 1h;
}
expires可以配置缓存时间,但是开发 / 测试环境尽量不用,否则可能造成新代码不生效灰度环境的实现方式
set $group "app_default";
if ($http_dangdang_umark = 0) {
set $group "app_normal";
}
if ($http_dangdang_umark = 1) {
set $group "app_huidu";
}
set $group "tomcat_default";
if($http_cookie ~* "dangdang_umark=0") {
set $group "tomcat_dangdang";
}
if ($http_cookie ~* "dangdang_umark=1") {
set $group "tomcat_huidu";
}
Nginx日志
error_log :
error_log /opt/nginx/logs/nginx_error.log crit;
access_log :
log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" - $http_x_forwarded_for - $http_x_real_ip - "$request_time"' ;
配置地址如下
access_log /opt/nginx/logs/access_log access;
可在http 或 server中配置。
Nginx服务常用命令
sbin/nginx -t -c /usr/local/nginx/conf/nginx.conf
sbin/nginx -c /usr/local/nginx/conf/nginx.conf
sbin/nginx -s reload
sbin/nginx -s stop
参考文档