具体配置可见

NGINX 配置

NGINX 入门学习笔记

NGINX 备忘清单

Web 服务器

nginx
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# http
server {
  listen 80;
  server_name _;
  location / {
    root /data;
    index index.html index.htm;
  }
}

# https
server {
  listen 443 ssl;
  server_name _;
  ssl_certificate /path/to/certificete.crt;
  ssl_certificate_key /path/to/private-key.key;
  location / {
    root /data;
    index index.html index.htm;
  }
}

反向代理

nginx
1
2
3
4
5
6
7
8
9
server {
  listen 80;
  server_name _;
  location / {
    proxy_pass http://192.168.241.11;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
  }
}

负载均衡

nginx
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
upstream web {
  ip_hash
  #会话保持
  server 192.168.241.22;
  server 192.168.241.23;
}
server {
  listen 80;
  server_name _;
  location / {
    proxy_pass http://web;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
  }
}

重定向

nginx
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# 老域名跳转新域名
server {
  listen 80;
  server_name old.cxk.cn;
  location / {
    rewrite ^/(.*)$ https://new.cxk.cn/$1;
  }
}

# 路径重定向
server {
  listen 80;
  server_name old.cxk.cn;
  location / {
    rewrite ^/old.cxk.cn/(.*)$ /new-path/$1;
  }
}

防盗链

nginx
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
server {
  listen 80;
  server_name _;
  location ~* \.(gif|jpg|jpeg|png) {
    valid_referers none blocked *.cxk.cn;
    if ($invalid_referer) {
      return 403;
    }
  }
}

手机端重定向 PC

nginx
1
2
3
4
5
6
7
8
9
server {
  listen 80;
  server_name _;
  location / {
    if ($http_user_agent ~* '(android|iphone|ipad)') {
      return ^/(.*)$ https://yd.cxk.cn/$1;
    }
  }
}

基于请求路径转发不同服务

nginx
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
server {
  listen 80;
  server_name _;
  location / {
    proxy_pass http://192.168.241.11;
    proxy_set_header Host $host;
    proxy_set_header X-Real_IP $remote_addr;
  }
  location /beijing {
    proxy_pass http://192.168.241.22;
    proxy_set_header Host $host;
    proxy_set_header X-Real_IP $remote_addr;
  }
  location /nanjing {
    proxy_pass http://192.168.241.23;
    proxy_set_header Host $host;
    proxy_set_header X-Real_IP $remote_addr;
  }
}