nginx工作小结(1)

Nginx命令行

默认启动方式,直接使用二进制程序,读取配置文件conf/nginx.conf

/usr/local/nginx/sbin/nginx

指定配置文件的启动方式,使用-c参数后指定的nginx.conf配置文件来启动nginx

/usr/local/nginx/sbin/nginx -c /tmp/nginx.conf

另行指定安装目录的启动方式

/usr/local/nginx/sbin/nginx -p /tmpr/nginx/

可以通过-g参数临时指定一些全局配置项,以使新的配置生效

/usr/local/nginx/sbin/nginx  -g  “pid /var/nginx/test.pid;”

## g参数的约束条件
一是指定的配置项不能与默认路径下的nginx.conf中国的配置项相冲突,否则无法启动;
二是以-g方式启动的Nginx服务执行其他命令行时,需要把-g参数也带上,如停止nginx服务
/usr/local/nginx/sbin/nginx  -g  “pid /var/nginx/test.pid;” -s stop

测试配置信息是否有错误

#  在不启动nginx情况下,使用-t参数仅测试配置文件是否有错误
/usr/local/nginx/sbin/nginx  -t

# 测试阶段不输出信息
/usr/local/nginx/sbin/nginx  -t  -q

显示版本信息

/usr/local/nginx/sbin/nginx  -v

显示编译阶段的参数

/usr/local/nginx/sbin/nginx  -V

快速停止服务

/usr/local/nginx/sbin/nginx  -s  stop
kill -s SIGTERM  nginx_pid(nginx master pid)

优雅停止服务

/usr/local/nginx/sbin/nginx  -s  quit

只停止某个worker进程

kill -s SIGTERM <nginx worker pid>

使运行中的nginx重读配置并生效

/usr/local/nginx/sbin/nginx  -s  reload
kill -s SIGHUP <nginx master pid>

日志文件回滚

/usr/local/nginx/sbin/nginx -s reopen
kill -s  SIGUSR1  <nginx master pid>

平滑升级nginx

kill  -s  SIGUSR2  <nginx master pid>
此时会将nginx的pid文件重命名,如将/usr/local/nginx/logs/nginx.pid rename为
/usr/local/nginx/logs/nginx.pid.oldbin
使用上述启动命令开启新的Nginx服务,这时通过ps命令可发现新旧版本的Nginx在同时运行
通过kill命令向旧版本的master进程发送SIGQUIT信号,以”优雅”的方式关闭旧版本的Nginx

显示命令行帮助

/usr/local/nginx/sbin/nginx -h
Nginx常用配置

nginx基本配置

http{
    gzip on;
    # 配置负载均衡
    upstream service{
        server 192.168.10.221:9091 weight 2;
        server 192.168.10.221:9092 weight 3;
        server 192.168.10.221:9093 weight 2;
    }
    
    # ip hash负载
    upstream backend { 
        ip_hash; 
        server backend1. example.com; 
        server backend2. example.com; 
        server backend3. example.com down;  #down表示上游服务器永久下线,只在使用ip_hash配置项时才有用
        server backend4. example.com; 
    }
    
    # 配置多个虚拟主机server
    server{
        listen [ip]:80;
        
        location /webstatic{
            
        }
        
        location ~*.(jpg|jpeg|png|jpe|gif)${
            
        }
    }
}

静态资源配置

location ~* /static/*.+\.(gif|jpg|png|css|js|flv|ico|swf)$ {
        alias /home/ubuntu/mywork/python/youhuiquan/website/static;
        expires 1d;  
#       proxy_pass http://static;
#       proxy_redirect off; 
#       proxy_cache_valid 200 302 1h; 
#       proxy_cache_valid 301 1h; 
#       proxy_cache_valid any 1h; 
        add_header Pragma public;
        add_header Cache-Control "public";
 }

移动端配置

location / {
    if ( $http_user_agent ~ "(MIDP)|(WAP)|(UP.Browser)|(Smartphone)|(Obigo)|(Mobile)|(AU.Browser)|(wxd.Mms)|(WxdB.Browser)|(CLDC)|(UP.Link)|(KM.Browser)|(UCWEB)|(SEMC\-Browser)|(Mini)|(Symbian)|(Palm)|(Nokia)|(Panasonic)|(MOT\-)|(SonyEricsson)|(NEC\-)|(Alcatel)|(Ericsson)|(BENQ)|(BenQ)|(Amoisonic)|(Amoi\-)|(Capitel)|(PHILIPS)|(SAMSUNG)|(Lenovo)|(Mitsu)|(Motorola)|(SHARP)|(WAPPER)|(LG\-)|(LG/)|(EG900)|(CECT)|(Compal)|(kejian)|(Bird)|(BIRD)|(G900/V1.0)|(Arima)|(CTL)|(TDG)|(Daxian)|(DAXIAN)|(DBTEL)|(Eastcom)|(EASTCOM)|(PANTECH)|(Dopod)|(Haier)|(HAIER)|(KONKA)|(KEJIAN)|(LENOVO)|(Soutec)|(SOUTEC)|(SAGEM)|(SEC\-)|(SED\-)|(EMOL\-)|(INNO55)|(ZTE)|(iPhone)|(Android)|(Windows CE)|(Wget)|(Java)|(curl)|(Opera)" ){
        rewrite ^.+ http://m.domainName.com/$uri;                
     }       
     rewrite ^.+ http://www.domainName.com/$uri;
}

服务负载均衡基本配置

location / {
    proxy_pass    http://service;
    #proxy_method  GET | POST 
    proxy_set_header   Host                 $host;
    proxy_set_header   X-Real-IP            $remote_addr;                   # 获取真实IP
    proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;     # 获取代理者的真实IP
    proxy_set_header   X-Forwarded-Proto    $http_x_forwarded_proto;
    proxy_set_header   Via                  "nginx";
    # proxy_redirect   http://service   http://service_others;  # service返回302或301的时候将会重定向到service_others路由
    # proxy_next_upstream[ error | timeout | invalid_header | http_500 | http_502 | http_503 | http_504 | http_404 | off]; # 当上游服务器出错的时候将继续转发到另一台上游服务器处理相同的请求
    client_max_body_size 60m;
}

uWSGI 配置

upstream django {
    # server unix:///path/to/your/mysite/mysite.sock; # for a file socket
    server 127.0.0.1:8001; # for a web port socket (we'll use this first)
}

# Finally, send all non-media requests to the Django server.
location / {
    uwsgi_pass  django;
    include     /path/to/your/mysite/uwsgi_params; # the uwsgi_params file you installed
}

php fastcgi配置

location ~ \.php$ {
		fastcgi_split_path_info ^(.+\.php)(/.+)$;
		# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
	
		# With php5-cgi alone:
		#fastcgi_pass 127.0.0.1:9001;
		# With php5-fpm:
		#fastcgi_pass unix:/var/run/php5-fpm.sock;
		#fastcgi_index index.php;
		#root          /home/crazysal/public_html;
		fastcgi_pass   127.0.0.1:9001;
		fastcgi_index  index.php;
		include fastcgi_params;
		fastcgi_param  SCRIPT_FILENAME $document_root$fastcgi_script_name;
	}

nginx解决图片资源没有后缀名访问时直接下载问题

location / {
    root /path/static;
    add_header content-type "image/jpeg";
    expires 1d;
    // ...其他相关的配置
}

nginx 配置错误码跳转页面

# 当服务端出现以下的状态码的时候将会跳转到50x的页面,此时还需要配置50x的页面
error_page  500 502 503 504   /50x.html;     
location = /50x.html {
    internal;               # 客户端无法直接访问,必须是由nginx服务器内部转发的
    root  errors/html;
}

# 为location配置一个名称 (也是只能内部转发)
error_page  500 502 503 504   = @errors;  
location  @errors {
    proxy_pass http://error_backend;
}

# location 查询顺序和优先级
1. 带有 = 精确匹配优先
2. 没有修饰符的精确匹配优先
3. 正则表达式按照它们在配置文件中定义的顺序
4. 带有 ^~ 修饰的开头匹配
5. 带有 ~ 或者 ~* 修饰的,如果正则与URI匹配
6. 没有修饰的,指定字符串与URI开头匹配

try_files

# 按照指定的顺序检查存在的文件,并且返回第一个找到的文件结果,如果所有文件都没有找到,那么将启用最后一个参数命名的内部重定向
upstream render_uri{
    server 127.0.0.1:9080 weight=9;
}

try_files path1  path2  @render
location @render{
    proxy_pass http://render_uri;
}

加证书SSL配置支持https

server {
        listen 443;
        listen [::]:443;

        charset UTF-8;
        server_name domain;
        gzip on;
        gzip_types application/json;        # text/html,application/json格式总是会被压缩


        ssl on;
        ssl_certificate /etc/nginx/ssl-certs/xx.crt;
        ssl_certificate_key /etc/nginx/ssl-certs/xx.key;


        error_log  /home/ubuntu/java/logs/nginx/nginx_error.log;
        access_log /home/ubuntu/java/logs/nginx/nginx_access.log main_log;

        root /home/ubuntu/test;
        index index.html;

        location /album { 
                proxy_pass    http://album;
                proxy_set_header   Host                 $host;
                proxy_set_header   X-Real-IP            $remote_addr;
                proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;
                proxy_set_header   X-Forwarded-Proto    $http_x_forwarded_proto;
                proxy_set_header   Via                  "nginx";
                client_max_body_size 60m;
        }


        location /dounile/images {
             root /home/ubuntu/java/dounile/images;
             expires 1d;
        }

        location /dounile {
                proxy_next_upstream http_502 http_504 timeout;      # 配置故障转移,如果服务出现502,504或者是timeout则将转发给下一个
                valid_referers blocked dtreess.com *.dtreess.com;   # 配置简单的防盗链,只有dtreess.com的域名下才能访问 
                proxy_pass    http://dounile;
                proxy_set_header   Host                 $host;
                proxy_set_header   X-Real-IP            $remote_addr;
                proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;
                proxy_set_header   X-Forwarded-Proto    $http_x_forwarded_proto;
                proxy_set_header   Via                  "nginx";
                client_max_body_size 60m;
        }
}

全局负载均衡

http{
    geo $geo{
        default default;
        203.101.10.10/24 A;     # 客户端满足IP段走A服务器
        109.23.23.10/28 B;      # 客户端满足IP段走B服务器
    }
    
    upstream default.server {
        server 192.168.10.1 weight=10;
    }
    
    upstream A.server{
        server 192.168.10.2 weight=10;
    }
    
    upstream B.server{
        server 192.168.10.3 weight=10;
    }
    
    server {
        listen 80;
        location / {
            proxy_pass: http://$geo.server/$request_uri;
        }
    }
}

rewrite 模块

# 执行url的重定向,有利于去掉恶意访问的url,也有利于搜索引擎优化
last: 完成重写指令,之后搜索相应的URI或location
break:完成重写指令
redirect:返回302的临时重定向,如果替换字段用http://开头则被使用
permanent:返回301永久重定向

nginx查看进程进行追踪

# 打开shell终端
strace -f pid

# 打开shell第二个终端
nginx -s reload

# 在上面的strace将跟踪进程启动过程并输出到控制台中

设置nginx常用的日志格式

log_format log_main_format '$ remote_addr - $ remote_user [$ time_local] $ request ' 'upstream_response_time $ upstream_response_time ' 'msec $ msec request_time $ request_time'; log_format up_head '$ remote_addr - $ remote_user [$ time_local] $ request ' 'upstream_http_content_type $ upstream_http_content_type';

nginx优化配置

1. 尽量提高单台机器的处理效率
2. 尽量降低单台机器的负载
3. 降低磁盘IO
4. 降低网络IO
5. 减少内存使用
6. 高效利用CPU

# nginx.config
user keithl;
work_processes 8;

http{
    events{
        use epoll;
        # worker_connections的设置与物理内存有关,因为系统可以打开的最大文件数与内存成正比,一般1G内存机器可以打开的文件数是10万个 
        worker_connections 1024;        # 并发总数 = work_processes * worker_connections,需要根据设置进程数和系统可以打开的文件数进行调整
        
    }
}
发布了63 篇原创文章 · 获赞 9 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/wind_602/article/details/82764496