nginx 基础入门
nginx配置文件:
下载解压 tar.gz
./configure编译构建
nginx:操作命令 nginx -s stop(快速停止)|quit(优雅停止,工作线程完成工作)|reload(重新加载配置文件)|reopen(重新打开日志文件)
quit:以启动nginx的用户关闭
reload:主进程接到重载配置文件信号,检查配置文件合法性,并尝试应用配置。应用成功后,启动新的工作进程,并向就的工作进程发送关闭进程的信号;应用配置失败,则回滚变化,继续使用旧的配置文件。旧的进程接到关闭的命令时,停吃接受新的请求,并继续服务当前请求直至结束,然后停止服务。
kill -s QUIT pid:优雅关机
nginx开启后主机无法访问虚拟机的nginx解决方案
-
ping虚拟机,判断是否防火墙问题
防火墙问题处理: iptables文件添加 -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT vi /etc/sysconfig/iptables [root@localhost ]# /sbin/iptables -I INPUT -p tcp --dport 80 -j ACCEPT [root@localhost ]# /etc/init.d/iptables save [root@localhost ]# /etc/init.d/iptables restart
centos iptables 防火墙:
禁用防火墙:systemctl disable firewalld
卸载防火墙:yum remove firewalld -y 使用下面的办法来恢复原来的习惯,同时解决iptables开机启动的问题。 yum install iptables-services -y systemctl enable iptables iptables服务会开机启动,自动从/etc/sysconfig/iptables 文件导入规则。 为了让/etc/init.d/iptables save 这条命令生效,执行如下: cp /usr/libexec/iptables/iptables.init /etc/init.d/iptables
nginx代理服务器设置: server { location / { proxy_pass http://localhost:8080/; //80端口下访问,除了特别定义的location,其它都转发给8080端口处理
开启反向代理缓存,并使用zone name为one的缓存。
proxy_cache one; #设置状态码为200 302过期时间为10分钟 proxy_cache_valid 200 302 10m; #设置状态码404的过期时间为1分钟 proxy_cache_valid 404 1m;
}
location ~ .(gif|jpg|png)$ { root /data/images; } }
nginx反向代理问题: ]:8080 failed (13: Permission denied) while connecting to upstream, 处理: SeLinux 一、关闭SeLinux 查看SELinux状态: 1、/usr/sbin/sestatus -v ##如果SELinux status参数为enabled即为开启状态 SELinux status: enabled 2、getenforce ##也可以用这个命令检查 关闭SELinux: 1、临时关闭(不用重启机器): setenforce 0 ##设置SELinux 成为permissive模式
setenforce 1 设置SELinux 成为enforcing模式
2、修改配置文件需要重启机器: 修改/etc/selinux/config 文件 将SELINUX=enforcing改为SELINUX=disabled 重启机器即可 二、执行下面的命令 setsebool -P httpd_can_network_connect 1
连接处理方法配置: --with-select_module:配置使用select --with-poll_module:配置使用poll linux2.6+:epoll
查看nginx 配置信息:安装使用配置-- [root@zookeeper nginx]# nginx -V nginx version: nginx/1.12.2 built by gcc 4.8.5 20150623 (Red Hat 4.8.5-16) (GCC) built with OpenSSL 1.0.2k-fips 26 Jan 2017 TLS SNI support enabled configure arguments: --prefix=/usr/share/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib64/nginx/modules --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --pid-path=/run/nginx.pid --lock-path=/run/lock/subsys/nginx --user=nginx --group=nginx --with-file-aio --with-ipv6 --with-http_auth_request_module --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module=dynamic --with-http_image_filter_module=dynamic --with-http_geoip_module=dynamic --with-http_sub_module --with-http_dav_module --with-http_flv_module --with-http_mp4_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_random_index_module --with-http_secure_link_module --with-http_degradation_module --with-http_slice_module --with-http_stub_status_module --with-http_perl_module=dynamic --with-mail=dynamic --with-mail_ssl_module --with-pcre --with-pcre-jit --with-stream=dynamic --with-stream_ssl_module --with-google_perftools_module --with-debug --with-cc-opt='-O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -m64 -mtune=generic' --with-ld-opt='-Wl,-z,relro -specs=/usr/lib/rpm/redhat/redhat-hardened-ld -Wl,-E'
配置日志级别: error_log /var/log/nginx/error.log debug; // debug,info,notice,warn,error,crit, or alert
测试配置文件合法性:nginx -t
loadblance:
round-robin:轮询,可以配置权重,默认策略,服务器性能均衡,不可以直接配置
least-connected:least_conn、最少连接
ip-hash:ip作为hask key,选择服务器,保障统一客户端能请求总是到达同一服务器
hash $request_uri:按请求url hash值分配服务器
least_time:最少平均延迟和最少活跃连接。
负载均衡: max_fails(默认1,一次无回复,则nginx认定服务器down), fail_timeout(默认10s,nginx标记服务器下线后,经过时间间隔后认定服务器down), and slow_start只对对服务器起作用 http{ ... upstream upblance { ip_hash; // ip_hash | least_conn | least_time server 192.168.126.128:8080 max_conns=2; //round-robin策略下,可配置 weight=2,权重;max_conns服务器最大连接数,超过,则将请求置于请求队列,超过队列大小,则报错 server localhost:8080; // 添加 backup 设置为备用服务器;添加down 暂时下线服务器;slow_start=30s慢启动,用户刚恢复的服务器; queue 100 timeout=70; //1.15.12版本及之后 }
server{ ...
location / { proxy_pass http://upblance; //http必须 }配置https server:可以使用openssl 生成相应的免费证书 server.key server.crt server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; servername ; root /usr/share/nginx/html;
ssl_certificate "server.crt"; ssl_certificate_key "server.key"; ssl_session_cache shared:SSL:1m; ssl_session_timeout 10m; ssl_ciphers HIGH:!aNULL:!MD5; ssl_prefer_server_ciphers on;
Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / { }
error_page 404 /404.html; location = /40x.html { }
error_page 500 502 503 504 /50x.html; location = /50x.html { } }
rewrite,重定向:定义一个新的server,重新指向 server { listen 80; server_name test.com; return 301 http://www.test.com$request_uri; //指向下面server
}
server { listen 80 default_server; listen [::]:80 default_server; server_name www.test.com; ... ...
one should simply define example.com, www.example.com, and “everything else”: server { listen 80; server_name example.comwww.example.com; ... }
server { listen 80 default_server; servername ; //指代所有其它 return 301 http://example.com$request_uri; }
websocket:101 switch protocal location /chat/ { proxy_pass http://192.168.7.133:8888/websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; // proxy_set_header Connection "upgrade"; // }
libxml2 + libxml2-devel
fastcgi:网关转发请求 示例,处理php请求:linux安装php-fpm fastcgi软件 location ~ .php$ { root html; fastcgi_pass localhost:9000; fastcgi_index index.php; include fastcgi.conf; //必要的配置 }
session持久化: upstream:ip_hash、hash、sticky 。。。
四层协议的转发、代理或者负载均衡:stream模块,平行 http stream { upstream streamhost { server 192.168.7.133:9090; }
server{ listen 9090; proxy_pass streamhost; proxy_timeout 3s; proxy_connect_timeout 1s; } }
访问控制: location / { deny 192.168.1.1; allow 192.168.1.0/24; allow 10.1.1.0/16; allow 2001:0db8::/32; deny all; } location / { proxy_pass http://upblance; deny 192.168.126.1; // address | CIDR | unix: | all;deny: Denies access for the specified network or address;allow: Allows access for the specified network or address. }
重新载入nginx配置文件是报错:nginx: [error] invalid PID number "" in "/run/nginx.pid"
解决:重新制定配置文件位置,然后再载入配置文件
nginx -c 路径/nginx.conf
nginx -s reload
nginx ssi:
。。。
with-http_addition_module:相应前后添加内容:
location / { proxy_pass http://upblance;
deny 192.168.126.1;
add_before_body /header/; add_after_body /footer/; } location /header/ { root /usr/share/nginx/html;
} location /footer/ { root /usr/share/nginx/html;
}
autoindex on:当请求资源目录下没有index时,自动展现目录下文件列表: location /autoindex/ { autoindex on; autoindex_exact_size on; autoindex_localtime on; root /usr/share/nginx/html; }
random_index on: 随机返回请求资源目录下资源: location /randomindex/ { random_index on; root /usr/share/nginx/html; }
gzip压缩:* ngx_http_gzip_module 实时压缩,每次读取资源压缩
gzip on; //启动压缩 gzip_min_length 1000; //需要压缩的最小长度,取自于 Content-Length” gzip_comp_level 6; //压缩比率,越大耗费的cpu越多 gzip_proxied expired no-cache no-store private auth; //根据请求和回复,决定是否启用代理压缩 gzip_types text/plain application/xml; //针对压缩的资源类型 gzip_disable "MSIE [1-6]."; //根据客户端 User-Agent进行设置,MSIE[1-6]微软1-6版本浏览器,或者基于微软浏览器内核的浏览器; //The special mask “msie6” (0.7.12) corresponds to the regular expression “MSIE [4-6].”, but works faster
rewrite==ngx_http_rewrite_module: rewrite regex replacement [flag]; rewrite /rewrite /; //路径包含rewrite的请求 rewrite /rewrite / permanent; // permanent 创建永久重定向301规则,重定向新的url,(浏览器更新书签、爬虫更新抓取内容)
rewrite ^/rewrite$ /; //严格的路径重定向 rewrite /rewrite/(.*) http://www.$1.com; //重定向路径包含http https,则直接重定向至replacement url;/rewrite/baidu =》http://www.baidu.com
flag: last:停止当前指令集,搜索与更改后的URI匹配的location brak:停止当前指令集 redirect:302临时重定向 permanent:301永久重定向
last 和 break一样 它们都会终止此 location 中其他它rewrite模块指令的执行, 但是 last 立即发起新一轮的 location 匹配 而 break 则不会。
- last – Stops execution of the rewrite directives in the current server or location context, but NGINX Plus searches for locations that match the rewritten URI, and any rewritedirectives in the new location are applied (meaning the URI can be changed again).
-
break – Like the break directive, stops processing of rewrite directives in the current context and cancels the search for locations that match the new URI. The rewrite directives in the new location are not executed.
重新后之前的请求参数会附加到新的url之后;在新的url之后添加 ?, 则抛弃之前的参数。 GET /rewrite/baidu?time=time() =》https://www.baidu.com/?time=time()
log参数:
自定义log profile:
同时也可以针对不同的server定义不同的 error 和 access log log_format test '$remote_addr - [$time_local] "$request" $status '; //日志标识 ... ... server { access_log /var/log/nginx/root.log test; //使用自定义的日志 profile }
log文件fd缓存: http{ open_log_file_cache max=1000 inactive=20s min_uses=2 valid=1m; //缓存打开的日志文件描述符 ....
限流:ngx_http_limit_req_module 限制请求处理速率,尤其是源自同一ip的请求:基于漏桶方法 http { limit_req_zone $binary_remote_addr zone=first:10m rate=1r/s; //定义 key为请求地址, zone名为first,容量为10m的共享内存区域(lru),处理速率限制为每秒1次。 limit_req_zone $server_name zone=perserver:10m rate=10r/s; //定义key为服务器名称,zone为perserver,容量为10m的共享内存区域(lru),处理速率限制为每秒10次。 ...
server {
...
location /search/ { limit_req zone=first burst=5; //使用共享内存区域first,设定爆发请求数不超过5,如果不希望延迟过量的请求,则尾部添加nodelay标识 limit_req zone=perserver burst=10; //多限制共存,并 }
如下:error log: 2018/07/20 03:03:40 [error] 9969#0: 714 limiting requests, excess: 5.213 by zone "first", client: 192.168.126.1, server: www.test.com, request: "GET / HTTP/1.1", host: "192.168.126.129" 2018/07/20 03:03:40 [error] 9969#0: 714 limiting requests, excess: 5.013 by zone "first", client: 192.168.126.1, server: www.test.com, request: "GET / HTTP/1.1", host: "192.168.126.129" 2018/07/20 03:03:41 [error] 9969#0: *715 limiting requests, excess: 5.037 by zone "first", client: 192.168.126.1, server: www.test.com, request: "GET / HTTP/1.1", host: "192.168.126.129
限制下载速率: location /randomindex/ { random_index on; root /usr/share/nginx/html; limit_rate_after 1m; //下载1m后开始限速 limit_rate 100k; //限制下载速率为1k/s }
鉴权ngx_http_auth_basic_module:用于保护特定url连接安全;针对不同的url可以生成不同的鉴权文件。
location / { proxy_pass http://upblance;
deny 192.168.126.1;
add_before_body /header/;
add_after_body /footer/;
limit_req zone=first burst=5;
auth_basic "default n";
auth_basic_user_file /etc/nginx/htpasswd; //鉴权文件
}
使用httpd-tools生成鉴权文件: [root@zookeeper nginx]# yum install httpd-tools //安装加密工具 [root@zookeeper nginx]# htpasswd –c /etc/nginx/htpasswd roger //生成用户名为roger的密码,并存放于文件/etc/nginx/htpasswd 文件中 [root@zookeeper nginx]# cat htpasswd roger:$apr1$c94VlRcs$fuU12rxXOVfxGNn8vGr8E //文件格式
防盗链,安全连接:ngx_http_secure_link_module: secure_link_secret:/prefix/hash/link location /securelink/ { root html; secure_link_secret test_secure; //用于检验请求连接, if ($secure_link = "") { //如果请求连接包含权限验证信息,则真正的请求会从请求连接分离出来存入$scure_link,否则的话置空 return 403; } rewrite ^ /securelink/$secure_link break; //break 必要 }
生成MD5 HASH: 请求资源/secure.html [root@zookeeper nginx]# echo -n 'secure.htmltest_secure' | openssl dgst -md5 (stdin)= 6da8690e402cd3b50da5d751d13b4ea8 生成请求连接: /securelink/secure.html http://192.168.126.129/securelink/6da8690e402cd3b50da5d751d13b4ea8/secure.html
secure_link、secure_link_md5: location /securelinkx { root html; secure_link $arg_md5,$arg_expires; //参数 md5、expires secure_link_md5 "$secure_link_expires$uri$remote_addr secure_test"; //secure_link_expires:用于内部获取expires;uri:请求路径;secure_test:添加的密参;remote_addr:注意获取的值;自选需要的参数 if ($secure_link = "") { return 403; }
if ($secure_link = "0") { return 410; } } 请求路径:/securelinkx/ md5: [root@zookeeper nginx]# echo -n '2147483647/securelinkx/192.168.126.1 securetest' | openssl md5 -binary | openssl base64 | tr +/ - | tr -d = Qia1rWs8Xx2ZZkkJ7I4_IQ 请求连接: http://192.168.126.129/securelinkx/?md5=Qia1rWs8Xx2ZZkkJ7I4_IQ&expires=2147483647
配置fastcgi wordpress: location /wordpress { root /var/www; fastcgi_pass localhost:9000; fastcgi_index index.php; include fastcgi.conf; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; }
静态文件提前压缩: http_gzip_static_module,直接读取压缩的资源 .gz格式, location ~ .(jpg|png|jpeg|bmp|gif|swf)$ { gzip_static on; root /usr/share/nginx/html/images; expires 1d; }
sub_filter: http_sub_module location / { sub_filter 'href="http://127.0.0.1:8080/' 'href="https://$host/'; sub_filter 'img src="http://127.0.0.1:8080/' 'img src="https://$host/'; sub_filter_once on; }
更多建议: