插件窝 干货文章 怎么使用nginx代理实现静态资源访问

怎么使用nginx代理实现静态资源访问

static 静态 Nginx location 205    来源:    2025-04-21

使用Nginx代理实现静态资源访问

Nginx是一个高性能的HTTP和反向代理服务器,非常适合用来提供静态资源服务。以下是使用Nginx代理实现静态资源访问的详细步骤:

1. 基本静态资源服务配置

server {
    listen 80;
    server_name example.com;

    location /static/ {
        alias /path/to/your/static/files/;

        # 启用目录列表(可选)
        autoindex on;

        # 设置缓存头
        expires 30d;
        add_header Cache-Control "public";
    }
}

2. 关键配置项说明

  • alias:指定静态资源文件的实际路径
  • root:也可以使用root代替alias,区别在于root会保留location中的路径部分
  • autoindex:是否显示目录列表
  • expires:设置资源缓存时间
  • add_header:添加HTTP响应头

3. 性能优化配置

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    root /path/to/static/files;
    expires 365d;
    access_log off;
    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;

    # 启用sendfile
    sendfile on;
    tcp_nopush on;
}

4. 跨域访问配置

如果需要允许跨域访问静态资源:

location /static/ {
    alias /path/to/static/files/;
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
}

5. 防止目录遍历攻击

location /static/ {
    alias /path/to/static/files/;

    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
    }

    # 禁止执行PHP等脚本文件
    location ~ \.php$ {
        deny all;
    }
}

6. 实际应用示例

假设你的静态资源存放在/var/www/static目录下:

server {
    listen 80;
    server_name static.example.com;

    location / {
        root /var/www/static;
        index index.html;

        # 启用缓存
        expires 1d;
        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;

        # 防止目录遍历
        location ~ /\. {
            deny all;
        }
    }

    # 单独配置图片缓存时间更长
    location ~* \.(jpg|jpeg|png|gif|ico)$ {
        root /var/www/static;
        expires 365d;
        access_log off;
    }
}

7. 配置完成后

  1. 测试Nginx配置是否正确:

    nginx -t
    
  2. 重新加载Nginx配置:

    nginx -s reload
    
  3. 访问静态资源:

    • 如果配置了index指令,访问http://static.example.com会显示index文件
    • 访问具体资源如http://static.example.com/image.jpg

通过以上配置,Nginx可以高效地提供静态资源服务,并具备良好的性能和安全性。