Nginx使用手册

1,129 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第6天,点击查看活动详情

Nginx手册

Nginx配置

1. 代理实战配置

  1. 首先安装nginx

  2. 将vue项目buid好(static文件夹和index.html)放入linux一个目录下,如放在usr/local/myproject下面

  3. 修改/usr/local/nginx/conf下的nginx.conf,配置改为如下

server {
listen 8091;
server_name localhost;

location / {
root usr/local/myproject;
try_files $uri $uri/ @router;
index index.html;
}

error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}

location @router {
rewrite ^.*$ /index.html last;
}
}
  1. 进入sbin目录下重启即可

nginx -s reload

2. 负载均衡配置

upstream redislock{
server 192.168.1.5:8083 weight=1;
server 192.168.1.5:8081 weight=1;
}

server {
listen 80;
server_name localhost;

#charset koi8-r;

#access_log logs/host.access.log main;

location / {
root html;
index index.html index.htm;
proxy_pass http://redislock;
}

Nginx基础命令

架构图:

微信截图_20200107205704.png

#默认方式启动
nginx

#指定配置文件启动
nginx -c /tmp/nginx.conf

#指定nginx程序目录启动
nginx -p /usr/local/nginx/

#快速停止
nginx -s stop

#优雅停止
nginx -s quit

#检查参数是否正确
nginx -t

#热转载配置文件
nginx -s reload

#重新打开日志文件
nginx -s reopen
  1. location 配置
#正则匹配
location ~* \.(png|jpg|css|js)$ {
    root /usr/static/;
}

#全路径匹配
location = /baidu.html {
    proxy_pass http://www.baidu.com;
}

location / {
    index test.html;
}
  1. 防盗链
location ~* \.(png|jpg|css|js)$ {
		    root E:/jianzhiWork/111/lunbo/;
		    valid_referers none blocked localhost;
            	if ($invalid_referer) {
            		return 403;
            	}
		}
  1. 黑名单
  • 先写一个ip.black文件,内容为
deny 192.168.0.106;
  • 在nginx里加入 include ip.black;
http {
    include       mime.types;
    include       ip.black;
    default_type  application/octet-stream;
  1. 限速

limit_rate 代表限速1M/s
limit_rate_after代表 下载文件时前10m不限制,后10m之后的才限制

location /download {
    alias /usr/download;
    limit_rate 1m;
    limit_rate_after 10m;

}
  1. 日志配置

微信截图_20200108210558.png

  1. 修改日志级别
error_log  logs/error.log  debug;
#error_log  logs/error.log  info;
  1. 代理配置
location = /baidu.html {
    		proxy_pass http://www.baidu.com;
		}
  1. 负载均衡配置

使用upstream模块

  upstream redislock{
    	server 192.168.1.5:8083 weight=1;
    	server 192.168.1.5:8081 weight=1;
    }

    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root  html;
            index  index.html index.htm;
            proxy_pass http://redislock;
        }

负载均衡算法介绍:

  • ll+weight 轮询+权重
  • ip_hash算法
  • url_hash
  • least_conn 最少链接
  • least_time 最小响应时间
  1. 配置缓存、缓存清除

Nginx简单调优

  1. worker进程数

worker_processes 2

  1. worker 连接数

worker_connections 1024

  1. worker绑定cpu,避免cpu切换带来的性能损耗