全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-20 7 分钟 ✍️ juanwangdev

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 会暴露目录结构,生产环境建议关闭
  • rootalias 区别: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 可启用目录浏览,但生产环境建议关闭

📝 发现内容有误?点击此处直接编辑

下一篇 → Nginx 简介
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库