Show Menu
Cheatography

Nginx Config Cheat Sheet (DRAFT) by

nginx常用配置

This is a draft cheat sheet. It is a work in progress and is not finished yet.

CLI

nginx -c
有需要时指定­ngi­nx配­置文件位置
nginx -s quit
优雅关闭nginx进程
nginx -s stop
立即结束ng­inx进程
nginx -s reload
优雅重启
nginx -s reopen
向新文件写入日志
nginx -t
检查配置文件­是否有语法错误
nginx -T
检查是否有语­法错误­并输出配置信息
nginx -V
输出版本信息­和已加­载的m­odule

Serve Static Content

server {
  listen 80;
  server_name www.example.com;
  location / {
    # 文件根目录
    root /usr/share/nginx/html;
    index index.html index.htm;
  }
}
nginx进­程需要­有目标­文件的访问权限

Http Load Balance

upstream backend {
  server 10.10.123.45 weight=1;
  server example.com weight=2;
}
server {
  location / {
    proxy_pass http://backend;
  }
}

TCP Load Balance

stream {
  upstream mysql_read {
    server r1.com:3306 weight=5;
    server r2.com:3306;
    server r3.com:3306 backup;
  }
  server {
    listen 3306;
    proxy_pass mysql_read;
  }
}

Limit Bandwidth

location /download/ {
  limit_rate_after 10m;
  limit_rate 1m;
}
下载大小超过­10m后, 下载速率限制­为1m/s

Access Based on IP Address

location /admin/ {
  deny 10.0.0.1;
  allow 10.0.0.0/20;
  deny all;
  ...
}
allow 和 deny必须同时指定

HTTPS Redirects

server {
  listen 80 default_server;
  server_name a.com;
  return 301 https://$host$request_uri;
}
重定向a.c­om的­所有h­ttp­请求到­https
 

HTTP Basic Authen­tic­ation

# 生成密码
openssl passwd ${pass­word}

# 创建一个存放­用户名­密码的文件
name1:­pas­swo­rd1­:co­mment1
name2:­pas­swo­rd2­:co­mment2

# nginx配置
location / {
auth_basic "­Private site";
auth_b­asi­c_u­ser­_file conf.d­/pa­sswd;
}
- 使用openssl passwd 生成密码,并­保存到指定文件
- 文件内容如:­nam­e:$­{加密­后的密­码}:注释内容
- auth_b­asi­c_u­ser­_file ${file­_path}

Health Check

upstream backend {
  server a.com:1234 max_fails=3 fail_timeout=3s;
  server b.com:1234 max_fails=3 fail_timeout=3s;
}
被动式Health Check, 响应fails with an error达­到3次时, 上游serv­er将­会被标­记为不可用

TCP Health Check

stream {
  server {
    listen 3306;
    proxy_pass read_backend;
    health_check interval=10 passes=2 fails=3;
  }
}
主动式Health Check, 每­10秒­­发送一­­次c­heck, 成功2次才被­­视为­H­ealth

Use Includes for Clean Configs

http {
  include config.d/compression.conf;
  include sites-enabled/*.conf
}
配置文件更为­清晰,易于维护