初识Nginx
最重要的几个使用场景:
- 静态资源服务
- 反向代理服务,包括缓存、负载均衡等
- API 服务,OpenResty
通常一个
URL请求先通过Nginx转发到应用服务,然后再去访问数据库。
下载和基础知识
- 下载Nginx: 从
nginx.org网站下载即可 - 参考文档:juejin.cn/post/696343…
一、基础配置
1.去掉不用的 Nginx 模块:
./configure --without-module1 --without-module2 --without-module3
例如:./configure --without-http_dav_module --without-http_spdy_module
#注意事项:配置指令是由模块提供的。确保你禁用的模块不包含你需要使用的指令!在决定禁用模块之前,应该检查Nginx文档中每个模块可用的指令列表。
2.进程相关的配置
worker_processes 8; #Nginx 进程数,建议按照CPU数目来指定,一般为它的倍数 (如,2个四核的CPU计为8)。
worker_rlimit_nofile 65535; #一个Nginx 进程打开的最多文件描述符数目
worker_connections 65535; #每个进程允许的最多连接数
3.监听端口
server {
listen 80; #监听端口
server_name www.mingongge.com; #域名信息
location / {
root /www/www; #网站根目录
index index.html index.htm; #默认首页类型
deny 192.168.2.11; #禁止访问的ip地址,可以为all
allow 192.168.3.44; #允许访问的ip地址,可以为all
}
if (!-e $request_filename) { #解决vue刷新404问题,伪静态
rewrite ^/(.*)$ /index.php?s=$1 last;
break;
}
}
4.小技巧补充:域名匹配的四种写法
精确匹配:server_name www.mingongge.com ;
左侧通配:server_name *.mingongge.com ;
右侧统配:server_name www.mingongge.* ;
正则匹配:server_name ~^www\.mingongge\.*$ ;
匹配优先级:精确匹配 > 左侧通配符匹配 > 右侧通配符匹配 > 正则表达式匹配
5.配置 Nginx 状态页面
[root@proxy ~]
# cat /usr/local/nginx/conf/nginx.conf… …location /NginxStatus {
stub_status on;
access_log on;
auth_basic "NginxStatus";
auth_basic_user_file conf/htpasswd;
}… …[root@proxy ~]
# /usr/local/nginx/sbin/nginx -s reload
6.Nginx 日志(访问与错误日志管理)
error_log /var/log/nginx/error.log warn;#配置错误日志的级别及存储目录
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"'; #配置日志的模式
access_log /var/log/nginx/access.log main; #配置访问日志存储目录
}
7.静态资源配置
server {
listen 80;
server_name mingongge.com;
location /static {
root /wwww/web/web_static_site;
}
}
或者
location /image {
alias /web/nginx/static/image/;
} 注意:使用alias末尾一定要添加/,并且它只能位于location中
8.反向代理
http {
upstream product_server {
127.0.0.1:8081;
}
upstream admin_server {
127.0.0.1:8082;
}
upstream test_server{
127.0.0.1:8083;
}
server {
#默认指向product的server
location / {
proxy_pass http://product_server;
}
location /product/{
proxy_pass http://product_server;
}
location /admin/ {
proxy_pass http://admin_server;
}
location /test/ {
proxy_pass http://test_server;
}
}
}
9.负载均衡
http指令块包含以下4个块:
- `http`
- `server`--对应一个/一组域名
- `upstream`--表示上游服务,当`nginx`需要与`tomcat`、企业内网等服务交互时就可以定义一个`upstream`
- `location`--一个`url`表达式 `http`指令块的所有指令都是由`http`模块解析执行的,也就是说`http`模块只能解析执行上面4种模块。
upstream server_pools {
server 192.168.1.11:8880 weight=5;
server 192.168.1.12:9990 weight=1;
server 192.168.1.13:8989 weight=6; #weigth参数表示权值,权值越高被分配到的几率越大
}
server {
listen 80;
server_name mingongge.com;
location / {
proxy_pass http://server_pools;
}
}