Nginx静态资源服务 #
一、静态资源服务概述 #
Nginx作为静态资源服务器是其最基础也是最重要的功能之一。相比动态内容处理,静态资源服务更加高效,Nginx在这方面表现尤为出色。
1.1 为什么选择Nginx #
- 高性能:基于事件驱动,轻松处理高并发
- 低内存:每个连接仅占用少量内存
- sendfile:零拷贝技术,高效传输文件
- 缓存支持:灵活的缓存策略
二、基本配置 #
2.1 最简配置 #
nginx
server {
listen 80;
server_name static.example.com;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
2.2 root与alias区别 #
root指令:
nginx
location /images/ {
root /var/www;
}
请求 /images/logo.png → 文件路径 /var/www/images/logo.png
alias指令:
nginx
location /images/ {
alias /var/www/img/;
}
请求 /images/logo.png → 文件路径 /var/www/img/logo.png
区别总结:
| 指令 | 说明 | URL映射 |
|---|---|---|
| root | 根目录 | URL路径追加到root后 |
| alias | 别名 | URL路径替换为alias路径 |
2.3 多目录配置 #
nginx
server {
listen 80;
server_name static.example.com;
location / {
root /var/www/html;
index index.html;
}
location /images/ {
alias /var/www/images/;
expires 30d;
}
location /videos/ {
alias /var/www/videos/;
mp4;
mp4_buffer_size 1m;
mp4_max_buffer_size 5m;
}
location /downloads/ {
alias /var/www/downloads/;
autoindex on;
}
}
三、目录浏览 #
3.1 启用目录浏览 #
nginx
location /downloads/ {
alias /var/www/downloads/;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
autoindex_format html;
}
| 指令 | 说明 | 默认值 |
|---|---|---|
| autoindex | 启用目录浏览 | off |
| autoindex_exact_size | 显示精确大小 | on |
| autoindex_localtime | 显示本地时间 | off |
| autoindex_format | 输出格式 | html |
3.2 格式选项 #
nginx
location /downloads/json/ {
alias /var/www/downloads/;
autoindex on;
autoindex_format json;
}
location /downloads/xml/ {
alias /var/www/downloads/;
autoindex on;
autoindex_format xml;
}
3.3 目录浏览美化 #
使用第三方模块如 ngx-fancyindex:
nginx
location /downloads/ {
alias /var/www/downloads/;
fancyindex on;
fancyindex_exact_size off;
fancyindex_localtime on;
fancyindex_name_length 255;
fancyindex_header /header.html;
fancyindex_footer /footer.html;
fancyindex_ignore "*.tmp";
}
四、文件类型处理 #
4.1 MIME类型配置 #
nginx
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
types {
application/javascript js;
text/css css;
image/png png;
image/jpeg jpg;
image/gif gif;
application/font-woff woff;
application/font-woff2 woff2;
}
}
4.2 自定义Content-Type #
nginx
location ~* \.(json|map)$ {
root /var/www/data;
default_type application/json;
add_header Content-Type "application/json; charset=utf-8";
}
location ~* \.(xml)$ {
root /var/www/data;
default_type application/xml;
add_header Content-Type "application/xml; charset=utf-8";
}
4.3 强制下载 #
nginx
location /downloads/ {
alias /var/www/downloads/;
if ($request_filename ~* ^.*?\.(txt|pdf|doc|docx|xls|xlsx)$) {
add_header Content-Disposition "attachment; filename=$arg_name";
}
}
或者使用 add_header:
nginx
location /files/ {
alias /var/www/files/;
add_header Content-Disposition "attachment";
}
五、缓存策略 #
5.1 浏览器缓存 #
nginx
location ~* \.(jpg|jpeg|png|gif|ico|webp)$ {
expires 30d;
add_header Cache-Control "public, immutable";
}
location ~* \.(css|js)$ {
expires 7d;
add_header Cache-Control "public";
}
location ~* \.(html|htm)$ {
expires 1h;
add_header Cache-Control "public, must-revalidate";
}
5.2 expires指令 #
nginx
expires epoch;
expires max;
expires off;
expires 30d;
expires 1h;
expires @15h;
expires -1;
| 值 | 说明 |
|---|---|
| epoch | 不缓存(1970年) |
| max | 永久缓存(2037年) |
| off | 不设置缓存头 |
| 时间 | 相对时间 |
| @时间 | 每天固定时间过期 |
5.3 Cache-Control详解 #
nginx
location /static/ {
alias /var/www/static/;
add_header Cache-Control "public";
add_header Cache-Control "private";
add_header Cache-Control "no-cache";
add_header Cache-Control "no-store";
add_header Cache-Control "max-age=86400";
add_header Cache-Control "must-revalidate";
add_header Cache-Control "immutable";
}
5.4 ETag配置 #
nginx
location /static/ {
alias /var/www/static/;
etag on;
etag_format W/"%X%Y";
}
六、性能优化 #
6.1 sendfile优化 #
nginx
http {
sendfile on;
tcp_nopush on;
tcp_nodelay on;
}
| 指令 | 说明 |
|---|---|
| sendfile | 使用内核级文件传输 |
| tcp_nopush | 优化数据包发送 |
| tcp_nodelay | 禁用Nagle算法 |
6.2 零拷贝原理 #
text
传统方式:
磁盘 → 内核缓冲区 → 用户缓冲区 → 内核Socket缓冲区 → 网卡
sendfile方式:
磁盘 → 内核缓冲区 → 内核Socket缓冲区 → 网卡
6.3 大文件传输优化 #
nginx
location /videos/ {
alias /var/www/videos/;
sendfile on;
tcp_nopush on;
output_buffers 1 2m;
aio on;
directio 5m;
}
6.4 连接优化 #
nginx
http {
keepalive_timeout 65;
keepalive_requests 1000;
open_file_cache max=10000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}
七、访问控制 #
7.1 IP访问控制 #
nginx
location /admin/ {
alias /var/www/admin/;
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
}
7.2 基于域名的访问控制 #
nginx
location /internal/ {
if ($host != "internal.example.com") {
return 403;
}
alias /var/www/internal/;
}
7.3 基于Referer防盗链 #
nginx
location /images/ {
alias /var/www/images/;
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
}
}
7.4 返回防盗链图片 #
nginx
location /images/ {
alias /var/www/images/;
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
rewrite ^/images/(.*)$ /hotlink.png last;
}
}
八、压缩配置 #
8.1 Gzip压缩 #
nginx
http {
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_buffers 16 8k;
gzip_http_version 1.1;
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml
application/xml+rss
application/x-javascript;
gzip_disable "msie6";
}
8.2 Brotli压缩 #
nginx
http {
brotli on;
brotli_comp_level 6;
brotli_types text/plain text/css application/json application/javascript;
brotli_min_length 1000;
}
8.3 预压缩文件 #
nginx
location /static/ {
alias /var/www/static/;
gzip_static on;
brotli_static on;
}
九、安全配置 #
9.1 隐藏版本号 #
nginx
http {
server_tokens off;
}
9.2 限制请求方法 #
nginx
location /static/ {
alias /var/www/static/;
if ($request_method !~ ^(GET|HEAD)$) {
return 405;
}
}
9.3 安全头配置 #
nginx
location /static/ {
alias /var/www/static/;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "strict-origin-when-cross-origin";
}
9.4 敏感文件保护 #
nginx
location ~* /\.(git|svn|htaccess|htpasswd|env) {
deny all;
return 404;
}
location ~* \.(log|bak|sql|conf|ini)$ {
deny all;
return 404;
}
十、完整配置示例 #
nginx
server {
listen 80;
server_name static.example.com;
access_log /var/log/nginx/static.access.log;
error_log /var/log/nginx/static.error.log;
root /var/www/static;
index index.html;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
open_file_cache max=10000 inactive=30s;
open_file_cache_valid 60s;
open_file_cache_min_uses 2;
location / {
try_files $uri $uri/ =404;
}
location ~* \.(jpg|jpeg|png|gif|ico|webp|svg)$ {
expires 30d;
add_header Cache-Control "public, immutable";
add_header X-Content-Type-Options "nosniff";
valid_referers none blocked server_names *.example.com;
if ($invalid_referer) {
return 403;
}
}
location ~* \.(css|js)$ {
expires 7d;
add_header Cache-Control "public";
gzip_static on;
}
location ~* \.(woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
add_header Access-Control-Allow-Origin "*";
}
location ~* /\.(git|svn|htaccess|htpasswd|env) {
deny all;
return 404;
}
location ~* \.(log|bak|sql|conf)$ {
deny all;
return 404;
}
}
十一、总结 #
本章我们学习了:
- 基本配置:root与alias的区别和使用
- 目录浏览:autoindex配置和美化
- 文件类型:MIME类型和强制下载
- 缓存策略:浏览器缓存配置
- 性能优化:sendfile、零拷贝、连接优化
- 访问控制:IP限制、防盗链
- 压缩配置:Gzip和Brotli
- 安全配置:隐藏版本、安全头
掌握静态资源服务后,让我们进入下一章,学习反向代理配置!
最后更新:2026-03-27