Nginx 常用配置备忘清单 | nginx-cheatsheet

作为软件开发工程师多多少少都该懂一些 nginx 的使用和配置,下面是 nginx 的几个经典应用场景下的配置写法,记录下来以防遗忘,用到的时候也可以直接过来拷贝。

端口监听

 1server {
 2  # Standard HTTP Protocol
 3  # 标准的 HTTP 协议
 4  listen 80;
 5
 6  # Standard HTTPS Protocol
 7  # 标准的 HTTPS 协议
 8  listen 443 ssl;
 9
10  # For http2
11  listen 443 ssl http2;
12
13  # Listen on 80 using IPv6
14  # 使用 IPv6 监听 80 端口
15  listen [::]:80;
16
17  # Listen only on using IPv6
18  # 仅使用 IPv6 监听 80 端口
19  listen [::]:80 ipv6only=on;
20}

访问日志

1server {
2  # Relative or full path to log file
3  # 为日志文件指定一个相对或绝对路径
4  access_log /path/to/file.log;
5
6  # Turn 'on' or 'off'
7  # 通过 'on' 或者 'off' 控制是否启用
8  access_log on;
9}

域名

指定域名和对应的网站根目录位置,server_name 可以是域名、二级域名,也可以是 ip 地址。

 1server {
 2  # Listen to yourdomain.com
 3  # 监听来自域名 yourdomain.com 的访问
 4  server_name yourdomain.com;
 5
 6  # Listen to multiple domains
 7  # 监听来自多个域名的访问
 8  server_name yourdomain.com www.yourdomain.com;
 9
10  # Listen to all domains
11  # 监听 yourdomain.com 的所有二级域名
12  server_name *.yourdomain.com;
13
14  # Listen to all top-level domains
15  # 监听所有 yourdomain 的顶级域名
16  server_name yourdomain.*;
17
18  # Listen to unspecified Hostnames (Listens to IP address itself)
19  # 不指定域名,监听自身 IP 的访问
20  server_name "";
21}

静态资源访问

1server {
2  listen 80;
3  server_name yourdomain.com;
4
5  location / {
6    root /path/to/website;
7  } 
8}

重定向

1server {
2  listen 80;
3  server_name www.yourdomain.com;
4  return 301 http://yourdomain.com$request_uri;
5}
1server {
2  listen 80;
3  server_name www.yourdomain.com;
4
5  location /redirect-url {
6    return 301 http://otherdomain.com;
7  }
8}

反向代理

 1server {
 2  listen 80;
 3  server_name yourdomain.com;
 4
 5  location / {
 6    proxy_pass http://0.0.0.0:3000;
 7    # where 0.0.0.0:3000 is your application server (Ex: node.js) bound on 0.0.0.0 listening on port 3000
 8  }
 9
10}

负载均衡

 1upstream node_js {
 2  server 0.0.0.0:3000;
 3  server 0.0.0.0:4000;
 4  server 123.131.121.122;
 5}
 6
 7server {
 8  listen 80;
 9  server_name yourdomain.com;
10
11  location / {
12     proxy_pass http://node_js;
13  }
14}

SSL 证书

 1server {
 2  listen 443 ssl;
 3  server_name yourdomain.com;
 4
 5  ssl on;
 6
 7  ssl_certificate /path/to/cert.pem;
 8  ssl_certificate_key /path/to/privatekey.pem;
 9
10  ssl_stapling on;
11  ssl_stapling_verify on;
12  ssl_trusted_certificate /path/to/fullchain.pem;
13
14  ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
15  ssl_session_timeout 1h;
16  ssl_session_cache shared:SSL:50m;
17  add_header Strict-Transport-Security max-age=15768000;
18}
19
20# Permanent Redirect for HTTP to HTTPS
21# 将 HTTP 访问永久重定向到 HTTPS
22server {
23  listen 80;
24  server_name yourdomain.com;
25  return 301 https://$host$request_uri;
26}

感谢

文中用到的配置几乎都出自 https://vishnu.hashnode.dev/nginx-cheatsheet 这篇文章,在此基础上经过个人理解添加了一些解释说明,特此说明。