插件窝 干货文章 linux服务器上如何使用nginx访问本地静态资源

linux服务器上如何使用nginx访问本地静态资源

Nginx 配置 server sudo 334    来源:    2025-04-23

使用Nginx访问本地静态资源的配置指南

在Linux服务器上使用Nginx访问本地静态资源是一个常见需求,以下是详细配置步骤:

1. 安装Nginx

如果尚未安装Nginx,请先安装:

# Ubuntu/Debian
sudo apt update
sudo apt install nginx

# CentOS/RHEL
sudo yum install epel-release
sudo yum install nginx

# 启动Nginx并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx

2. 基本配置

编辑Nginx配置文件(通常位于/etc/nginx/nginx.conf/etc/nginx/sites-available/default):

sudo nano /etc/nginx/sites-available/default

添加或修改server块配置:

server {
    listen 80;
    server_name your_domain_or_ip;

    location /static/ {
        alias /path/to/your/static/files/;
        autoindex on;  # 可选:启用目录列表
    }

    # 其他配置...
}

3. 详细配置选项

基本静态文件服务

server {
    listen 80;
    server_name example.com;

    location / {
        root /var/www/html;
        index index.html index.htm;
    }
}

多个静态资源目录

server {
    listen 80;
    server_name example.com;

    location /images/ {
        alias /data/images/;
        expires 30d;  # 缓存30天
    }

    location /downloads/ {
        alias /data/downloads/;
        autoindex on;  # 显示目录列表
    }
}

性能优化配置

server {
    # ...其他配置...

    location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
        root /var/www/html;
        expires 365d;
        access_log off;
        add_header Cache-Control "public";
    }
}

4. 权限设置

确保Nginx用户(通常是www-datanginx)有权限访问静态资源目录:

sudo chown -R www-data:www-data /path/to/your/static/files
sudo chmod -R 755 /path/to/your/static/files

5. 测试并重启Nginx

# 测试配置是否正确
sudo nginx -t

# 重启Nginx使配置生效
sudo systemctl restart nginx

6. 验证访问

在浏览器中访问:

http://your_server_ip/static/

或者使用curl测试:

curl http://localhost/static/

高级配置选项

  1. Gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
  1. 防盗链
location ~* \.(jpg|jpeg|png|gif)$ {
    valid_referers none blocked yourdomain.com *.yourdomain.com;
    if ($invalid_referer) {
        return 403;
    }
}
  1. 限制访问
location /private/ {
    alias /path/to/private/files/;
    allow 192.168.1.0/24;
    deny all;
}

通过以上配置,您可以在Linux服务器上使用Nginx高效地提供静态资源服务。