HTTP服务器与静态资源服务
Nginx 原生支持 HTTP 协议,是高性能静态资源服务的理想选择。
HTTP 服务器基础配置
监听端口与域名
nginx
server {
listen 80;
server_name www.example.com example.com;
}
文档根目录
nginx
server {
listen 80;
root /var/www/html;
index index.html index.htm;
}
静态资源服务
基本配置
nginx
server {
listen 80;
server_name static.example.com;
location / {
root /data/static;
autoindex off;
}
}
文件类型与 MIME
nginx
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
}
静态资源优化
nginx
server {
location /static/ {
root /data/www;
# 启用 sendfile 零拷贝
sendfile on;
# 启用 TCP nopush
tcp_nopush on;
# 启用 TCP nodelay
tcp_nodelay on;
# 设置过期时间
expires 30d;
add_header Cache-Control "public, immutable";
}
}
目录浏览
启用目录列表功能:
nginx
location /files/ {
root /data;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
autoindex_format html;
}
注意事项
autoindex on会暴露目录结构,生产环境建议关闭root与alias区别:root会拼接 location 路径,alias会替换路径- 静态资源建议设置缓存头,减少重复传输
root 与 alias 区别
nginx
# root:请求 /images/logo.png → 查找 /data/images/logo.png
location /images/ {
root /data;
}
# alias:请求 /images/logo.png → 查找 /var/www/static/logo.png
location /images/ {
alias /var/www/static/;
}
常见静态资源类型配置
图片
nginx
location ~* \.(jpg|jpeg|png|gif|ico|svg)$ {
root /data/images;
expires 30d;
access_log off;
}
CSS/JS
nginx
location ~* \.(css|js)$ {
root /data/assets;
expires 7d;
add_header Cache-Control "no-transform";
}
字体文件
nginx
location ~* \.(woff|woff2|ttf|eot)$ {
root /data/fonts;
expires 30d;
add_header Access-Control-Allow-Origin *;
}
要点总结
- Nginx 原生支持 HTTP 协议,配置简单高效
root指令指定文档根目录,index指定默认首页- 静态资源服务建议开启 sendfile、设置过期时间
root拼接路径,alias替换路径,两者作用不同- 图片、CSS、JS 等静态资源建议设置较长缓存时间
autoindex可启用目录浏览,但生产环境建议关闭
📝 发现内容有误?点击此处直接编辑