nginx 常用配置

windows 平台注意

使用cmd进入nginx所在目录,使用cmd命令行启动nginx,不要双击不然更新配置(reload)不生效。

nginx.exe start # 后台运行
nginx -s stop  快速关闭 nginx
nginx -s quit  优雅的关闭 nginx
nginx -s reload  重新加载配置
nginx -s reopen  重新打开日志文件


nginx.exe # 前台运行,cmd不关闭

不同路径转发不同端口服务器:

server {
    listen       80;
    server_name  localhost;

    location ^~ /tomcat1/ {
        proxy_pass   http://localhost:18080/;
    }
    
    location ^~ /tomcat2/ {
        proxy_pass   http://127.0.0.1:28080/;
    }

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

}

location 常用配置

#直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,官网如是说。
#这里是直接转发给后端应用服务器了,也可以是一个静态首页
# 第一个必选规则
location = / {
    proxy_pass http://tomcat:8080/index
}
 
# 第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项
# 有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用
location ^~ /static/ {                              //以xx开头
    root /webroot/static/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {     //以xx结尾
    root /webroot/res/;
}
 
#第三个规则就是通用规则,用来转发动态请求到后端应用服务器
#非静态文件请求就默认是动态请求,自己根据实际把握
location / {
    proxy_pass http://tomcat:8080/
}

root 和 alias

# root
location /i/ {
    root /data/w3;
}

请求:http://xxxx.../i/top.gif 
路径:/data/w3/i/top.gif


# alias
location /i/ {
    alias /data/w3/;
}
请求:http://xxxx.../i/top.gif 
路径:/data/w3/top.gif

负载均衡

http {
    ...

    upstream testBalancing {
        server localhost:18080 weight=1; 
        server localhost:28080 weight=2; 
    }
    # down 表示单前的server临时不參与负载.
    # weight 默觉得1.weight越大,负载的权重就越大
    # backup: 其他全部的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻
    
    server {
        listen       83;
        server_name  localhost;
        
        location / {
            proxy_pass http://testBalancing;
            proxy_redirect default;
        }
    }
}

gzip

在http模块加配置:

# 开启gzip
gzip  on;
# 启用gzip压缩的最小文件,小于设置值的文件将不会压缩
gzip_min_length 1k;
# gzip 压缩级别,1-10,数字越大压缩的越好,也越占用CPU时间。一般设置1和2
gzip_comp_level 2;
# 进行压缩的文件类型。javascript有多种形式。其中的值可以在 mime.types 文件中找到。
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
# 是否在http header中添加Vary: Accept-Encoding,建议开启
gzip_vary on;
# 禁用IE 6 gzip
gzip_disable "MSIE [1-6]\.";
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Nginx常用命令 启动 Nginx 停止 Nginx Nginx 重载配置 上述是采用向 Nginx 发送信号的...
    Rick617阅读 2,158评论 0 8
  • ubuntu的目录结构和说明 ps:其他系统目录结构可能不一样,但是配置文件都是一样通用的,这里简单说一下ubun...
    曹渊说创业阅读 316评论 0 0
  • nginx配置文件主要分成四部分: main:全局设置,main部分设置的指令将影响其它所有部分的设置; serv...
    YONGSSU的技术站点阅读 1,414评论 0 0
  • HTTP模块(核心模块,也是主要用到的模块) server模块 server模块是http的子模块,它用来定义一个...
    临冬zx阅读 414评论 1 0
  • 可能經常瀏覽微拍堂,覺得有一種對抗叫競拍: 面對羊脂白玉,國之重器有的人可能無動於衷,因為缺...
    冰梦吴卫阅读 261评论 7 3