nginx安装

2023/4/5 Install

# 账号准备

# 1.新建用户

sudo useradd -m -d /home/包名 -s /bin/bash 用户名
1

# 2.设置密码

passwd 用户名
1

# 准备依赖

# nginx-1.27.0.tar.gz
https://pan.baidu.com/s/1KfpCrwjtZH1mSdB9l8EFzw?pwd=3cqw
# zlib-1.2.12.tar.gz
https://pan.baidu.com/s/1cN8-GQNwjPKQoNH04DQPSw?pwd=euyk 
# pcre-8.45.zip
https://pan.baidu.com/s/1t6Bd1oB1gv0CPdYQ_ZwmKg?pwd=4rs6
# openssl-3.3.1
https://pan.baidu.com/s/14BrAoKtJul7RyGI-Y1Szzg?pwd=eays
1
2
3
4
5
6
7
8

# 执行部署

# 1.安装编译工具(外网)

# yum工具
yum install -y gcc-c++	zlib zlib-devel	openssl openssl-devel pcre pcre-devel

# apt工具(注意可能包名不一样)
apt -y install make zlib zlib-devel gcc-c++ libtool  openssl openssl-devel
# 查询包
apt search 
# 下载
apt install -y
1
2
3
4
5
6
7
8
9

# 2.安装需要的组件(内网)

# 2.1、安装openssl
tar -zxf openssl-3.3.1.tar.gz
# 进入目录																				
cd openssl-3.3.1/
# 指定编译安装路径	
./configure --prefix=/home/common/openssl-3.3.1
# 编译安装																				
make && make install

# 2.2、安装pcre
# 解压
unzip pcre-8.45.zip
# 进入目录																				
cd pcre-8.35/
# 指定路径																	
./configure --prefix=/home/common/pcre-8.45
# 编译安装																				
make && make install

# 2.3 安装zlib
# 解压
tar -zxf  zlib-1.2.12.tar.gz
# 进入目录
cd zlib-1.2.12/
# 指定路径
./configure --prefix=/home/common/zlib-1.2.12
# 编译安装
make && make install
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

# 3.安装nginx

# 解压
tar -zxf nginx-1.27.0.tar.gz
# 进入目录
cd nginx-1.27.0/
# 3.1、常规模块安装(有外网的情况,重点是提示缺什么就安装什么)
./configure --prefix=/home/common/nginx-1.27.0 \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module \
--with-http_stub_status_module \
--with-pcre
    
# 3.2、使用安装包的(内网的情况)
./configure --prefix=/home/common/nginx-1.27.0 \				
	--with-openssl=../openssl-3.3.1 \						
    --with-pcre=../pcre-8.45 \							
    --with-zlib=../zlib-1.2.12

#编译安装    
make && make install
#注意:如果安装完以后没有logs目录,则自己手动创建一个
vim conf/nginx.conf
# 验证Nginx配置文件语法问题
sbin/nginx -t
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

# 4.启动

# 4.1、启动nginx服务进程
sbin/nginx -p $(pwd)

# 4.2、脚本编辑
#!/bin/bash
pkill nginx
sleep 1
sbin/nginx -p $(pwd)
echo "nginx started!"

# 4.3、开机启动
# 创建服务文件
sudo vim /etc/systemd/system/nginx.service
# 写入以下内容(请根据你的实际路径修改 ExecStart、PIDFile 等)
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
User=common
Group=common
PIDFile=/home/common/nginx-1.27.0/logs/nginx.pid
ExecStartPre=/home/common/nginx-1.27.0/sbin/nginx -t
ExecStart=/home/common/nginx-1.27.0/sbin/nginx
ExecReload=/home/common/nginx-1.27.0/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

# 可选:限制权限(更安全)
NoNewPrivileges=true
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target

# 重新加载 systemd 并启用
sudo systemctl daemon-reexec
sudo systemctl enable nginx
sudo systemctl start nginx
sudo systemctl status nginx
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

# 5.注意事项

# 注意:非root是不能监听 1024 以下的端口
# 5.1、使用 CAP_NET_BIND_SERVICE 能力(推荐)
sudo setcap 'cap_net_bind_service=+ep' /usr/sbin/nginx

# 5.2、使用 iptables 端口转发
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080

# 5.3、使用 systemd 配置(配合 Capabilities)
# 在 systemd 服务文件中设置
[Service]
User=nginx
AmbientCapabilities=CAP_NET_BIND_SERVICE
1
2
3
4
5
6
7
8
9
10
11
12

# 验证部署

# 查看nginx进程是否存在
ps -ef|grep nginx|grep -v grep

# 查看nginx服务端口
netstat -ntpl|grep 8080

#注意浏览器访问的话需要注意是否开启了防火墙
1
2
3
4
5
6
7

# 配置讲解

全局块 (main:进程数、用户、日志、PID文件等)
├── events块 (事件模型配置:连接处理模型、并发连接数等)
└── http块 (HTTP服务器配置:MIME类型、日志格式、GZIP压缩等)
    ├── upstream块 (上游配置:负载均衡服务器组定义)
    ├── server块 (服务器配置:虚拟主机、监听端口、域名等)
    │   ├── location块 (位置配置:URL路径匹配、代理、重写规则等)
    │   ├── location块 (位置配置:URL路径匹配、代理、重写规则等)
    │   └── ...
    ├── server块 (虚拟主机2)
    └── ...
├── mail块 (邮件代理配置,可选)
└── stream块 (TCP/UDP代理配置,可选)
1
2
3
4
5
6
7
8
9
10
11
12
# ============================================
# 全局块 - 主配置文件开始
# ============================================

# 定义运行Nginx的用户和用户组
# 语法:user [user] [group];
# 默认:user nobody nobody;
user nginx nginx;

# Nginx进程数,建议设置为等于CPU总核心数
# auto:自动检测CPU核心数
worker_processes auto;

# 错误日志定义,级别为:debug|info|notice|warn|error|crit
# 语法:error_log file [level];
error_log /var/log/nginx/error.log warn;

# 进程PID文件位置
pid /var/run/nginx.pid;

# 指定进程可以打开的最大文件描述符数量
worker_rlimit_nofile 65535;

# 加载动态模块
# load_module modules/ngx_http_geoip_module.so;

# ============================================
# 事件块 - 事件模型配置
# ============================================
events {
    # 设置网络连接序列化,防止惊群现象
    accept_mutex on;
    
    # 设置一个进程是否同时接受多个网络连接
    multi_accept on;
    
    # 事件驱动模型,可选:select|poll|kqueue|epoll|rtsig|/dev/poll|eventport
    use epoll;
    
    # 单个工作进程的最大连接数
    # 最大客户端连接数 = worker_processes * worker_connections
    worker_connections 1024;
}

# ============================================
# HTTP块 - HTTP服务器配置
# ============================================
http {
    # 包含MIME类型定义文件
    include /etc/nginx/mime.types;
    
    # 默认MIME类型
    default_type application/octet-stream;
    
    # 定义日志格式
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    
    log_format json '{"@timestamp":"$time_iso8601",'
                    '"remote_addr":"$remote_addr",'
                    '"remote_user":"$remote_user",'
                    '"request":"$request",'
                    '"status":"$status",'
                    '"body_bytes_sent":"$body_bytes_sent",'
                    '"http_referer":"$http_referer",'
                    '"http_user_agent":"$http_user_agent",'
                    '"http_x_forwarded_for":"$http_x_forwarded_for",'
                    '"request_time":"$request_time"}';
    
    # 访问日志设置
    access_log /var/log/nginx/access.log main;

    #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
    #sendfile指令指定 nginx 是否调用sendfile 函数(zero copy 方式)来输出文件,对于普通应用,必须设为on。如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络IO处理速度,降低系统uptime。
    sendfile on;
    
    # 防止网络阻塞,在高负载下告诉nginx在一个数据包里发送所有头文件
    tcp_nopush on;
    
    # 在keepalive连接上禁用Nagle算法
    tcp_nodelay on;
    
    # 客户端连接超时时间
    keepalive_timeout 65;
    
    # 客户端请求头缓冲区大小
    client_header_buffer_size 4k;
    
    # 客户端请求头超时时间
    client_header_timeout 15;
    
    # 客户端请求体超时时间
    client_body_timeout 15;
    
    # 客户端请求体最大值
    client_max_body_size 100m;
    
    # 重置超时连接
    reset_timedout_connection on;
    
    # 隐藏Nginx版本号,增强安全性
    server_tokens off;
    
    # 设置字符集
    charset utf-8;
    
    # ============================================
    # GZIP压缩配置
    # ============================================
    gzip on;                            # 开启gzip压缩
    gzip_static on;
	gzip_proxied any;
    gzip_min_length 1k;                 # 最小压缩文件大小
    gzip_comp_level 6;                  # 压缩级别1-9,数字越大压缩率越高
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;  # 压缩类型
    gzip_vary on;                       # 根据Accept-Encoding头返回不同内容
    gzip_disable "MSIE [1-6]\.";        # 对IE6禁用gzip
    gzip_buffers 16 8k;                 # gzip缓冲区
    gzip_http_version 1.1;              # 启用gzip的HTTP最低版本
    
    # ============================================
    # 上游服务器配置(负载均衡)
    # ============================================
    upstream backend_servers {
        # 负载均衡算法,可选:ip_hash|least_conn|hash key|random
        least_conn;
        
        # 服务器定义,weight=权重,max_fails=最大失败次数,fail_timeout=失败超时时间
        server 192.168.1.10:8080 weight=5 max_fails=3 fail_timeout=30s;
        server 192.168.1.11:8080 weight=3 max_fails=3 fail_timeout=30s;
        server 192.168.1.12:8080 weight=2 max_fails=3 fail_timeout=30s;
        server 192.168.1.13:8080 backup;  # 备份服务器
    }
    
    # ============================================
    # 虚拟主机1 - 默认服务器
    # ============================================
    server {
        # server级别的allow/deny会影响所有location(如果location有就会被覆盖)
        allow 192.168.1.0/24;
        deny all;
    
        # 监听端口和协议
        listen 80 default_server;
        listen [::]:80 default_server;
        
        # 服务器名称,支持通配符和正则表达式
        server_name localhost example.com *.example.com;
        
        # 网站根目录
        root /usr/share/nginx/html;
        
        # 默认索引文件
        index index.html index.htm index.php;
        
        # 访问日志
        access_log /var/log/nginx/host.access.log main;
        
        # ============================================
        # 根路径配置
        # ============================================
        location / {
            #vue 项目目部署路径
            root   /usr/share/nginx/html/; 
            
            # 尝试访问文件,如果不存在则返回index.html
            try_files $uri $uri/ /index.html last;

            # 默认的首页文件,多个用空格分开
            index  index.html index.htm; 
            
            # 添加安全头
            add_header X-Frame-Options "SAMEORIGIN" always;
            add_header X-XSS-Protection "1; mode=block" always;
            add_header X-Content-Type-Options "nosniff" always;
        }
        
        # ============================================
        # 静态资源缓存配置
        # ============================================
        location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|txt)$ {
            # 缓存1年
            expires 1y;
            add_header Cache-Control "public, immutable";
            # 建议:在实际部署中,最好为这些静态资源文件名添加哈希指纹。
            # 这样,文件内容变化时URL也会变,就能安全地使用长期缓存了。
            
            # 文件不存在时不记录错误日志
            log_not_found off;
            
            # 开启文件额外属性,提高性能
            open_file_cache max=1000 inactive=20s;
            open_file_cache_valid 30s;
            open_file_cache_min_uses 2;
            open_file_cache_errors on;
        }
        
        # ============================================
        # PHP处理配置
        # ============================================
        location ~ \.php$ {
            # FastCGI配置
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
            
            # 超时设置
            fastcgi_connect_timeout 60s;
            fastcgi_send_timeout 60s;
            fastcgi_read_timeout 60s;
            
            # 缓冲区设置
            fastcgi_buffer_size 64k;
            fastcgi_buffers 4 64k;
            fastcgi_busy_buffers_size 128k;
        }
        
        # ============================================
        # 反向代理配置
        # ============================================
        location /api/ {
            # 代理到上游服务器组
            proxy_pass http://backend_servers;
            proxy_redirect default;
            proxy_http_version 1.1;
            
            # 代理头信息
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            
            # 超时设置
            proxy_connect_timeout 30s;
            proxy_send_timeout 30s;
            proxy_read_timeout 30s;
            
            # 缓冲区设置
            proxy_buffering on;
            proxy_buffer_size 4k;
            proxy_buffers 8 4k;
            
            # 重试机制
            proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
            proxy_next_upstream_tries 3;
        }

        # 系统临时维护请打开下面这行注释,并重启nginx,维护完毕后请注释下年这行,并重启nginx
 		# rewrite ^(.*)$ /maintainace.html break;
        
        # ============================================
        # 安全配置 - 禁止访问敏感文件
        # ============================================
        location ~ /\.(ht|git|svn) {
            deny all;         # 拒绝其他所有IP
            access_log off;
            log_not_found off;
        }
        
        location ~ /\.env {
            deny all;         # 拒绝其他所有IP 
            return 404;
        }
        
        # ============================================
        # Nginx状态监控
        # ============================================
        location /nginx_status {
            stub_status on;           # 开启状态统计
            access_log off;           # 关闭访问日志
            allow 127.0.0.1;          # 只允许本地访问 可以直接加在location模块下
            allow 192.168.1.0/24;     # 允许内网访问 可以直接加在location模块下
            deny all;                 # 拒绝其他所有IP 可以直接加在location模块下
        }
        
        # ============================================
        # 错误页面配置
        # ============================================
        error_page 404 /404.html;
        error_page 500 502 503 504 /50x.html;
        
        location = /50x.html {
            root /usr/share/nginx/html;
            internal;  # 标记为内部位置,外部无法直接访问
        }
        
        location = /404.html {
            root /usr/share/nginx/html;
            internal;
        }
    }
    
    # ============================================
    # 虚拟主机2 - HTTPS配置示例
    # ============================================
    server {
        listen 443 ssl http2;
        listen [::]:443 ssl http2;
        
        server_name secure.example.com;
        
        # 网站根目录
        root /usr/share/nginx/secure;
        index index.html;
        
        # SSL证书配置
        ssl_certificate /etc/ssl/certs/example.com.crt;
        ssl_certificate_key /etc/ssl/private/example.com.key;
        
        # SSL协议配置
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384;
        ssl_prefer_server_ciphers off;
        
        # SSL会话缓存
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
        
        # HSTS头
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        
        location / {
            try_files $uri $uri/ /index.html;
        }
    }
    
    # ============================================
    # 虚拟主机3 - 重定向HTTP到HTTPS
    # ============================================
    server {
        listen 80;
        server_name secure.example.com;
        
        # 301永久重定向到HTTPS
        return 301 https://$server_name$request_uri;
    }
    
    # ============================================
    # 包含其他配置文件
    # ============================================
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

# ============================================
# 邮件代理配置(可选)
# ============================================
#mail {
#    server_name mail.example.com;
#    auth_http localhost:9000/auth;
#    
#    proxy_pass_error_message on;
#    
#    smtp_capabilities "SIZE 10485760" ENHANCEDSTATUSCODES 8BITMIME DSN;
#    
#    server {
#        listen 25;
#        protocol smtp;
#    }
#    
#    server {
#        listen 110;
#        protocol pop3;
#    }
#}

# ============================================
# Stream块 - TCP/UDP代理配置(四层负载均衡)
# ============================================
#stream {
#    upstream database_servers {
#        server 192.168.1.20:3306 weight=1;
#        server 192.168.1.21:3306 weight=2;
#    }
#    
#    server {
#        listen 3306;
#        proxy_pass database_servers;
#        proxy_timeout 3s;
#        proxy_connect_timeout 1s;
#    }
#}
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384

# 网站配置SSL证书

SSL证书(Secure Sockets Layer Certificate)是一种数字证书,用于加密在客户端和服务器之间传输的数据。它是一种安全协议,用于确保数据的保密性、完整性和身份验证。

SSL证书的作用是通过使用公钥加密技术,加密敏感信息,使其在互联网上的传输过程中不易被窃取和篡改。它还可以验证服务器的身份,确保用户与正确的网站建立安全连接,防止中间人攻击。

使用SSL证书可以提供以下几个主要的安全功能:

  1. 数据加密:SSL证书通过加密敏感数据,使其不易被恶意方获得。
  2. 身份验证:SSL证书验证服务器的身份,确保用户连接到正确的网站。
  3. 数据完整性:SSL证书使用数字签名技术,确保传输的数据在传输过程中没有被篡改。
  4. SEO优化:搜索引擎通常更喜欢使用SSL加密的网站,将其排名更靠前。

# .cer,.key,.pem文件的作用

.cer、.key 和 .pem 是常见的文件扩展名,用于存储不同类型的加密证书和密钥。

  1. .cer 文件:通常是 X.509 数字证书的扩展名。它包含了公钥、证书持有者的信息以及证书颁发机构的数字签名。.cer 文件用于验证服务器的身份,确保与其建立的连接是安全的。

  2. .key 文件:通常是私钥文件的扩展名。私钥是密钥对中的一部分,用于解密经由公钥加密的数据或生成数字签名。.key 文件通常与证书配对使用,用于服务器身份验证和安全通信。

  3. .pem 文件:PEM(Privacy Enhanced Mail)是一种基于 ASCII 编码的文件格式,可以存储多种类型的证书和密钥。.pem 文件可以包含证书、私钥、公钥以及其他相关信息。它是一种灵活的格式,可以用于存储各种加密相关的内容。

server {
    listen 443 ssl;
    server_name your_domain.com;

    #生成的证书位置
    ssl_certificate /etc/nginx/ssl/your_certificate.pem;
    ssl_certificate_key /etc/nginx/ssl/your_private_key.key;

    # 可选:配置其他 SSL 参数
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;

    # 其他服务器配置...
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 相关命令

#安装nginx
yum install nginx

#看是否有nginx进程
netstat -anput | grep nginx

#查看服务器端口占用情况
netstat -ntlp

#nginx重启
nginx -s reload

#关闭nginx
#快速停止nginx
nginx -s stop
#完整有序的停止nginx
nginx -s quit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 阻止特定国家的 IP 访问

# 第1步:安装GeoIP模块

Nginx需要借助GeoIP模块来识别客户端的地理位置信息。如果你使用的是Nginx主分支,可以通过以下命令安装该模块:

sudo apt-get install nginx-module-geoip # 对于基于Debian的系统
sudo yum install nginx-mod-http-geoip # 对于RPM-based系统
1
2

# 第2步:下载GeoIP数据库

GeoIP模块需要数据库文件来映射IP地址到国家。你可以从MaxMind的官方网站(https://dev.maxmind.com/geoip/geoip2/geolite2/)免费下载GeoIP.dat和GeoLiteCity.dat两个文件

下载后,将文件放置到Nginx配置文件指定的路径,如/etc/nginx/geoip/

# 第3步:配置Nginx在/etc/nginx/conf.d/下,编写geoip.conf文件如下:

geoip_country /etc/nginx/geoip/GeoIP.dat;
geoip_city /etc/nginx/geoip/GeoLiteCity.dat;
1
2

编辑Nginx的配置文件,通常是/etc/nginx/nginx.conf添加以下配置段:

map $geoip_country_code $allowed_country {
       default yes;
       US no; # 禁止从美国的访问,这里只是示例,可以根据需要修改国家代码
   }

   server {
       listen 80;
       server_name example.com;

       if ($allowed_country = no) {
           return 403;
       }

       # 其他配置...
   }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

在上述配置中,我们使用了geoip_country指令指定了 GeoIP 数据库的路径。然后,通过map指令创建了一个变量$allowed_country,根据国家代码判断是否允许访问。如果$allowed_country的值为no,则返回 403 禁止访问。