前言
在现代前端开发中,我们往往需要将打包后的静态资源(HTML、CSS、JS、图片等)上传至服务器,再借助轻量级高性能的 Nginx 来进行静态资源托管和反向代理。本文将带你从安装、目录布局,到 Nginx 配置细节,参数含义及性能安全优化,全方位剖析如何使用 Nginx 部署前端应用。
Nginx 简介与安装
Nginx 是一款高性能、高并发且低内存占用的 HTTP 服务器,也常被用作反向代理、负载均衡器和邮件代理服务器。
在 Linux 上安装
以 Ubuntu/Debian 为例:
1
2
| sudo apt update
sudo apt install nginx -y
|
RedHat/CentOS:
1
2
| sudo yum install epel-release -y
sudo yum install nginx -y
|
安装完成后,可通过:
1
2
3
| nginx -v # 查看版本
sudo systemctl start nginx
sudo systemctl enable nginx
|
来启动并设置开机自启。
项目目录结构示例
假设我们已有一个前端项目,打包后文件放在 /var/www/myapp:
1
2
3
4
5
6
7
8
9
| /var/www/myapp
├── index.html
├── favicon.ico
├── css/
│ └── app.xxx.css
├── js/
│ └── app.xxx.js
└── static/
└── images/…
|
可根据实际项目进行调整,例如 React、Vue 等框架打包输出路径不同。
Nginx 基本配置示例
在 /etc/nginx/nginx.conf 或新建 conf.d/myapp.conf:
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
| # /etc/nginx/nginx.conf(全局配置)
user www-data;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
# 日志格式
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/conf.d/*.conf;
}
|
在 conf.d/myapp.conf 中加入:
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
| server {
listen 80;
server_name example.com www.example.com;
root /var/www/myapp;
index index.html;
# 支持 SPA 前端路由
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源缓存
location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico)$ {
expires 30d;
add_header Cache-Control "public";
}
# Gzip 压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_min_length 1024;
# 错误页
error_page 404 /404.html;
location = /404.html {
internal;
}
}
|
常用配置参数详解
全局与事件模块
worker_processes
定义 Nginx 工作进程数。建议配置为 CPU 核心数或 auto,以充分利用多核。worker_connections
每个工作进程的最大连接数。理论最大并发 = worker_processes × worker_connections。
HTTP 模块
include mime.types
加载 MIME 类型映射,使浏览器能识别文件类型。sendfile on
开启高效文件传输。keepalive_timeout
保持 TCP 连接的超时时间,减少短链接握手开销。
Server 模块(虚拟主机)
listen 80 / listen 443 ssl http2
指定监听端口与协议,启用 HTTP/2 需 http2 标志。server_name
匹配请求的域名,可写多个。root
指定站点根目录。index
默认访问的首页文件。
Location 模块
location /path
精确或前缀匹配请求 URI,支持正则: location ~ \.php$。try_files $uri $uri/ /index.html
用于 SPA:优先返回静态资源,若不存在则回退到 index.html 交由前端路由处理。
反向代理
1
2
3
4
5
6
| location /api/ {
proxy_pass http://127.0.0.1:3000/;
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_pass:将匹配请求转发到后端地址。proxy_set_header:设置或覆盖转发时的 HTTP 头,保持真实 IP、域名等。
静态资源缓存
1
2
3
4
| location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico)$ {
expires 30d;
add_header Cache-Control "public";
}
|
expires:控制浏览器缓存时长。add_header Cache-Control:细化缓存策略,例如 must-revalidate、no-transform 等。
Gzip 压缩
1
2
3
4
| gzip on;
gzip_min_length 1024;
gzip_proxied any;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml+rss;
|
gzip on/off:开启或关闭 Gzip。gzip_min_length:超过此长度才压缩,避免小文件压缩后更大。gzip_types:指定压缩的 MIME 类型。
SSL/TLS 加密
1
2
3
4
5
6
7
8
9
| server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/ssl/certs/example.com.crt;
ssl_certificate_key /etc/ssl/private/example.com.key;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_prefer_server_ciphers on;
}
|
ssl_certificate / ssl_certificate_key:证书与私钥路径。ssl_protocols:允许的协议版本,推荐只启用 TLSv1.2+。ssl_ciphers:指定加密套件。http2:启用 HTTP/2,提升并发性能。
示例:部署 Vue/React 单页应用
以打包后文件位于 /var/www/myapp 为例,新建 nginx 配置 /etc/nginx/conf.d/myapp.conf:
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
| server {
listen 80;
server_name myapp.example.com;
root /var/www/myapp;
index index.html;
# 路由回退
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源缓存优化
location ~* \.(?:css|js|woff2?|ttf|svg|eot)$ {
expires 365d;
add_header Cache-Control "public, immutable";
}
location ~* \.(?:png|jpg|jpeg|gif|ico)$ {
expires 30d;
add_header Cache-Control "public";
}
# Gzip
gzip on;
gzip_min_length 1000;
gzip_types text/plain text/css application/json application/javascript image/svg+xml;
# 可选:反向代理 API
location /api/ {
proxy_pass http://backend:8080/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
# 自定义错误页
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
|
部署完后:
1
2
| sudo nginx -t # 测试配置语法
sudo systemctl reload nginx
|
访问 http://myapp.example.com 即可看到应用。
性能优化与安全加固
开启 HTTP/2:listen 443 ssl http2;
使用 Brotli:在编译或安装时加入 ngx_brotli 模块,压缩率更高。
限速限流:
1
2
3
4
5
6
7
8
| limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
server {
...
location /api/ {
limit_req zone=one burst=20 nodelay;
proxy_pass http://backend;
}
}
|
防盗链:
1
2
3
4
5
6
| location ~* \.(jpg|png|gif|svg)$ {
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403;
}
}
|
HTTP 安全头:
1
2
3
4
| add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header Referrer-Policy no-referrer-when-downgrade;
add_header Content-Security-Policy "default-src 'self';";
|
日志切割:结合 logrotate,定期归档访问日志和错误日志。
常见问题与注意事项
404 页面刷新空白:若 SPA 路由刷新报 404,需确保 try_files … /index.html 配置生效。
编码乱码:可在 http {} 或 server {} 中添加:
文件权限:root 指定的目录需对 nginx 用户可读。
端口占用:确保 80、443 端口未被其他服务占用。
HTTPS 强制跳转:可在 80 端口的 server 中添加
1
| return 301 https://$host$request_uri;
|
热部署:使用 inotify、rsync、CI/CD(如 GitLab CI、GitHub Actions)自动同步静态文件并热 reload。