Nginx

Nginx Liemer_Lius 5954℃

nginx -h

# nginx -h
nginx version: nginx/1.18.0
Usage: nginx [-?hvVtTq] [-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  # 显示版本和编译时候的cnofigure信息
  -t            : test configuration and exit                   # 测试配置文件
  -T            : test configuration, dump it and exit          # 测试配置文件,并集合所有配置并打印出来
  -q            : suppress non-error messages during configuration testing      # 配合-t,不显示配置ok的提示信息
  -s signal     : send signal to a master process: stop, quit, reopen, reload   # 可接受的信号:stop强停,quit优雅地停,reopen重新打开日志文件(等于kill -USR1),reload,优雅地重新启动(先quit,再启动)
  -p prefix     : set prefix path (default: /usr/local/nginx-1.18.0/)
  -c filename   : set configuration file (default: conf/nginx.conf)             # 指定配置文件
  -g directives : set global directives out of configuration file               # nginx -g 'daemon off;',固定用发,nginx在前台运行,如docker中一般保持nginx【pid=1】前台运行,否则docker在启动后pid的进程销毁,健康检查失败就停止了。

负载均衡

这里,nginx.conf中添加include conf.d/*.conf;配置,在conf.d下建立独立的配置文件:

> vim admin.conf
upstream admin{
server 192.168.80.12:8080;
server 192.168.80.13:8080;
}

server {
    listen       8090;
    server_name  admin;

    location ^~ /lius-release {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header Host test-lius.skelchina.com;
        proxy_pass http://admin;
    }
}

其中,12和13,分别是两台tomcat,8080端口中有配置的测试程序,其中两个程序中的内容不一样,为了便于测试,将index.html里的内容用文本002和003替换。

server的监听测试中使用了8090,location中匹配lius-release进行代理。

测试中,使用浏览器的话,因为缓存的原因,导致不会按照轮询的方式每次都切换,因此采用shell后台curl的形式测试:

# curl http://192.168.80.11:8090/lius-release/
002
# curl http://192.168.80.11:8090/lius-release/
003
# curl http://192.168.80.11:8090/lius-release/
002
# curl http://192.168.80.11:8090/lius-release/
003

可以看到,每次切换都会不一样。

如果要不停服变更,只需要将一个节点的upstream配置变为down,另一个配置为backup,重载nginx就可以了。

> vim admin.conf   # 下面仅列出变动的配置
upstream admin{
server 192.168.80.12:8080 backup;
server 192.168.80.13:8080 down;
}
> /usr/local/nginx-1.18.0/sbin/nginx -s reload
# curl http://192.168.80.11:8090/lius-release/   # 不再变动
002
# curl http://192.168.80.11:8090/lius-release/
002
# curl http://192.168.80.11:8090/lius-release/
002

2、访问安全配置

# 原文链接:https://blog.csdn.net/u010505805/article/details/94616791
server
{
    listen 80;
    server_name www.5isousuo.com www.liqinglin.cn www.5wwfu6.cn;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/qqbt.app/public;
        location / {
                #禁止Scrapy等工具的抓取
                if ($http_user_agent ~* (Scrapy|Curl|HttpClient)) {
                     return 403;
                }
                #禁止指定UA及UA为空的访问
                if ($http_user_agent ~* "FeedDemon|Indy Library|Alexa Toolbar|AskTbFXTV|AhrefsBot|CrawlDaddy|CoolpadWebkit|Java|Feedly|UniversalFeedParser|ApacheBench|Microsoft URL Control|Swiftbot|ZmEu|oBot|jaunty|Python-urllib|lightDeckReports Bot|YYSpider|DigExt|HttpClient|MJ12bot|heritrix|EasouSpider|Ezooms|^$" ) {
                     return 403;             
                }
                #禁止非GET|HEAD|POST方式的抓取
                if ($request_method !~ ^(GET|HEAD|POST)$) {
                    return 403;
                }
        index  index.php index.html index.htm;
         #如果请求既不是一个文件,也不是一个目录,则执行一下重写规则
         if (!-e $request_filename)
         {
            #地址作为将参数rewrite到index.php上,让路由支持pathonfo模式。
            rewrite ^/(.*)$ /index.php?s=$1 last;
            #若是子目录则使用下面这句,将subdir改成目录名称即可。
            #rewrite ^/subdir/(.*)$ /subdir/index.php?s=$1;
         }
        client_max_body_size 100m;
        #配置如果是OPTIONS方法直接返回204状态
      if ($request_method = 'OPTIONS') {
           add_header 'Access-Control-Allow-Origin' '*' always;
           add_header 'Access-Control-Allow-Credentials' 'true';
           add_header 'Access-Control-Allow-Methods' 'GET, POST, PATCH, DELETE, PUT, OPTIONS';
           add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,  Access-Control-Expose-Headers, Token, Authorization';
           add_header 'Access-Control-Max-Age' 1728000;
           add_header 'Content-Type' 'text/plain charset=UTF-8';
           add_header 'Content-Length' 0;
           return 204;
      }   
    }
    #SSL-START SSL相关配置,请勿删除或修改下一行带注释的404规则
    #error_page 404/404.html;
    #SSL-END
    
    #ERROR-PAGE-START  错误页配置,可以注释、删除或修改
    error_page 404 /404.html;
    error_page 502 /502.html;
    #ERROR-PAGE-END
    
    #PHP-INFO-START  PHP引用配置,可以注释或修改
    include enable-php-72.conf;
    #PHP-INFO-END
    
    #REWRITE-START URL重写规则引用,修改后将导致面板设置的伪静态规则失效
    include /www/server/panel/vhost/rewrite/qqbt.app.conf;
    #REWRITE-END
   
    #禁止访问的文件或目录
    location ~ ^/(\.user.ini|\.htaccess|\.git|\.svn|\.project|LICENSE|README.md)
    {
        return 404;
    }
    
}

2、Reload之后长连接超时强制退出

Worker shutdown timeout

NGINX 1.11.11 introduced a new worker_shutdown_timeout directive to automatically close connections and shut down worker processes after a specified time.

Syntax:	worker_shutdown_timeout time;   # 例如:worker_shutdown_timeout 10s;
Default:	—
Context:	main
This directive appeared in version 1.11.11.
Configures a timeout for a graceful shutdown of worker processes. When the time expires, nginx will try to close all the connections currently open to facilitate shutdown.

实例:

#user  nobody;
worker_processes  auto;
worker_shutdown_timeout 10m;   # 与worker_process处于一个级别的配置

默认单位是s,不加单位即可;

单位支持h(小时)、m(分钟)、s(秒),不支持min之类的非简写模式。

3、nginx服务

service管理

#!/bin/bash
#chkconfig: 2345 85 15   
# Nginx management script for service.

nginxd=/usr/local/openresty/nginx/sbin/nginx
nginx_config=/usr/local/openresty/nginx/conf/nginx.conf
nginx_pid=/usr/local/openresty/nginx/logsnginx.pid
RETVAL=0
prog="nginx"
 
 
. /etc/rc.d/init.d/functions
. /etc/sysconfig/network
[ "x${NETWORKING}" = "xno" ] && exit 0
[ -x $nginxd ] || exit 0
 
 
start() {
    if [ -e $nginx_pid ];then
        echo "nginx already running...."
        exit 1
    fi
    echo -n $"Starting $prog: "
    daemon $nginxd -c ${nginx_config}
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && touch /var/lock/subsys/nginx
    return $RETVAL
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $nginxd
    RETVAL=$?
    echo
    [ $RETVAL = 0 ] && rm -f /var/lock/subsys/nginx /var/run/nginx.pid
}

reload() {
    echo -n $"Reloading $prog: "
    #kill -HUP `cat ${nginx_pid}`
    killproc $nginxd -HUP
    RETVAL=$?
    echo
}

case "$1" in
    start)
        start
        ;;
    stop)
        stop
        ;;
    reload)
        reload
        ;;
    restart)
        stop
        start
        ;;
    status)
        status $prog
        RETVAL=$?
        ;;
    *)
        echo $"Usage: $prog {start|stop|restart|reload|status|help}"
        exit 1
esac
exit $RETVAL

管理命令:
chkconfig --add nginx
service nginx stop
service nginx start
service nginx raload
service nginx status
service nginx restart

 

systemctl管理

# vim /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx  web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
 
[Service]
Type=forking
PIDFile=/usr/local/openresty/nginx/logs/nginx.pid
ExecStartPre=/usr/local/openresty/nginx/sbin/nginx -t -c /usr/local/openresty/nginx/conf/nginx.conf
ExecStart=/usr/local/openresty/nginx/sbin/nginx -c /usr/local/openresty/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
 
[Install]
WantedBy=multi-user.target

管理命令:
systemctl daemon-reload
systemctl start nginx
systemctl status nginx
systemctl enable nginx
systemctl is-enabled nginx

Location

https://www.cnblogs.com/ronghua/p/13043466.html

语法规则: location [=|~|~*|^~] /uri/ {… }
首先匹配 =,其次匹配^~,其次是按文件中正则的先后顺序匹配,当有匹配成功时候,停止匹配并按当前匹配规则处理请求,其他正则无法匹配则最后交由/通配。

 

测试使用的模块【类似echo】

location = /lius {
    default_type 'text/plain';
    return 200 "lius1";
}

 

openresty做成服务:

# vim /usr/lib/systemd/system/nginx.service
[Unit]
Description=nginx  web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target


[Service]
Type=forking
PIDFile=/usr/local/openresty/nginx/logs/nginx.pid
ExecStartPre=/usr/local/openresty/nginx/sbin/nginx -t -c /usr/local/openresty/nginx/conf/nginx.conf
ExecStart=/usr/local/openresty/nginx/sbin/nginx -c /usr/local/openresty/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target

 

 

转载请注明:liutianfeng.com » Nginx

喜欢 (3)

评论已关闭。