Nginx 实战

Author Avatar
Klein 3月 12, 2024

记录下之前 Nginx 实际业务应用。

实际需求1:根据设备是否移动端自动跳转到不同的项目

实际需求2:/v2_cs 跳转到另外的项目

实际需求3:HTTPS

实际需求4:HTTP 强制跳转 HTTPS

实际需求5:多个域名共用一个项目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

# nginx.conf
worker_processes 1;

events {
worker_connections 1024;
}


http {
include mime.types;
default_type application/octet-stream;

sendfile on;

keepalive_timeout 65;

server {
listen 8080;
server_name localhost;

location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
include servers/*;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# servers/brand.conf
map $http_referer $v2_cs_referer {
default 0;
~*v2_cs 1;
}

map $http_user_agent $fe {
default fe_pc;
~*Mobile fe_mobile;
}

upstream fe_pc {
server backend1.example.com:8080;
}

upstream fe_mobile {
server backend1.example.com:8082;
}

server {
listen 80;
listen [::]:80;
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name "~^(misets|just|papa)\.xyz$";
index index.php index.html index.htm default.php default.htm default.html;

#HTTP_TO_HTTPS_START
if ($server_port !~ 443){
rewrite ^(/.*)$ https://$host$1 permanent;
}
#HTTP_TO_HTTPS_END

ssl_certificate ../cert/papa.xyz+8.pem;
ssl_certificate_key ../cert/papa.xyz+8-key.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

location ^~ /mobile-future-alpha {
proxy_pass https://localhost:9000;
include servers/proxy_params.conf;
error_log off;
}

location /v2_customer_service {
include proxy_params.conf;
proxy_pass https://localhost:9000;
}

location / {
proxy_pass https://$fe;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header HTTP_X_FORWARDED_FOR $remote_addr;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}

access_log logs/brand_access.log;
error_log logs/brand_error.log;
}