全局指令
指令 | 值 |
---|---|
user | 出于安全考虑,默认是nginx、nobody |
worker_processes | 工作进程数,一般来说,设置与CPU的核心数相同即可 |
error_log | 保存错误日志的路径,可以设置error_log的级别 |
pid | nginx 进程id |
user nginx; worker_processes 4; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { # 每秒处理多少个客户端连接 worker_connections 1024; } http { include /etc/nginx/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"'; access_log /var/log/nginx/access.log main; sendfile on; tcp_nopush on; #与客户端保持连接的最长时间 keepalive_timeout 65; gzip on; include /etc/nginx/conf.d/*.conf; }
日志分析
- ngxtop 流量实时监测 https://github.com/lebinh/ngxtop,这个简直就是神器(o^^o)
- goaccess 日志可视化 https://github.com/allinurl/goaccess
- goaccess 分析配置 https://github.com/stockrt/nginx2goaccess
- goaccess 操作说明 https://www.fanhaobai.com/2017/06/go-access.html
日志分割
日积月累,nginx 的日志文件也会变得越来越大,如果我们是自己编译安装的nginx,可能就需要自己来处理日志文件的分割了。定时分割日志文件,这有利于降低单个文件的大小,方便排查,同时只保留最近一段时间的日志,也可以节省磁盘空间
一般采用 logrotate 来进行日志文件的分割:https://linux.die.net/man/8/logrotate
# USR1 re-opening log files http://nginx.org/en/docs/control.html # daily 每天处理一次 # missingok 忽略文件不存在的错误 # rotate 设置旧文件保留的数量 # compress 对日志进行压缩 # delaycompress 延迟压缩 # notifempty 如果文件内容为空,不处理 # create 设置文件权限、用户、组 # sharedscripts 对于prerotate和postrotate脚本,如果匹配到了多个日志文件,只运行一次脚本。如果没有匹配到,则不运行。 # postrotate表示在日志rotate之后,执行的脚本 /var/log/nginx/*.log { daily missingok rotate 30 compress delaycompress notifempty create 640 nginx nginx sharedscripts postrotate if [ -f /var/run/nginx.pid ]; then kill -USR1 `cat /var/run/nginx.pid` fi endscript }
测试 logrotate 配置是否生效
logrotate -v /etc/logrotate.conf
调试定时任务,不会处理实际文件
logrotate -vf /etc/logrotate.conf
立刻执行所有任务,不管是否已到执行时间,会处理实际文件
server配置
server { listen 80; server_name localhost; #nginx程序默认的web根目录 location / { root /usr/share/nginx/html; index index.html index.htm; } error_page 404 /404.html; # 重定向服务器的错误页到指定的静态页面 /50x.html error_page 500 502 503 504 404 /50x.html; location = /50x.html { root /usr/share/nginx/html; } location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; } }
当我们配置好了Nginx,就可以使用curl来进行初步的测试了:
curl -v http://127.0.0.1/ > /dev/null
倘若我们想禁止用户通过IP或者未设置的域名来访问,可以采取如下措施:
server { listen 80 default; rewrite ^(.*) http://www.example.com permanent; }
变量
变量类型 | 变量列表 |
---|---|
内置变量 | http://nginx.org/en/docs/varindex.html |
HTTP请求变量 | http://nginx.org/en/docs/http/ngx_http_core_module.html#var_status |
参考文档:http://www.ttlsa.com/nginx/nginx-var-1/
路由
如果我们想要访问/path/to/name,那么 Nginx 配置中,路由匹配的优先级如下
修饰符 | 说明 | 优先级 |
---|---|---|
location = /path/to/name | 精确匹配 | 1 |
location /path/to/name | 完整匹配 | 2 |
location ^~ /path/to/name | 表示uri以某个常规字符串开头,非正则表达式 | 3 |
location ~* /path/to/name | 使用不区分大小写的正则来进行匹配 | 4 |
location ~ /path/to/name | 使用区分大小写的正则来进行匹配 | 4 |
location /path | 部分匹配 | 5 |
location / | 通用匹配 | 6 |