logo 个人代码分享
服务器配置

Nginx 静态站点配置详解

Nginx 作为高性能 HTTP 服务器,非常适合托管静态站点。

Nginx 简介

Nginx 是一款轻量级的 Web 服务器/反向代理服务器,以其高性能、稳定性和低资源消耗而闻名。对于静态站点托管,Nginx 是理想的选择。

为什么选择 Nginx

  • 高性能:采用事件驱动架构,能够处理大量并发连接
  • 低内存占用:相比 Apache,Nginx 的内存占用更低
  • 配置简单:配置文件结构清晰,易于理解和维护
  • 丰富的功能:支持反向代理、负载均衡、缓存等功能

基本配置

以下是一个基本的 Nginx 静态站点配置:

server {
    listen 80;
    server_name hefei.space www.hefei.space;
    root /www/wwwroot/hefei.space;
    index index.html;

    # 日志配置
    access_log /var/log/nginx/hefei.space.access.log;
    error_log /var/log/nginx/hefei.space.error.log;

    # 静态文件缓存
    location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
        expires 7d;
        add_header Cache-Control "public, immutable";
    }

    # 路由配置
    location / {
        try_files $uri $uri/ /index.html;
    }
}

HTTPS 配置

现代网站应该启用 HTTPS。以下是启用 HTTPS 的配置:

server {
    listen 80;
    server_name hefei.space www.hefei.space;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    server_name hefei.space www.hefei.space;

    ssl_certificate /etc/nginx/ssl/hefei.space.pem;
    ssl_certificate_key /etc/nginx/ssl/hefei.space.key;

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    root /www/wwwroot/hefei.space;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

性能优化

Gzip 压缩

启用 Gzip 压缩可以显著减少传输数据量:

gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types
    text/plain
    text/css
    text/javascript
    application/javascript
    application/json
    application/xml
    image/svg+xml;

浏览器缓存

合理配置浏览器缓存可以减少重复请求:

# 静态资源缓存
location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
}

# HTML 文件不缓存
location ~* \.html$ {
    expires -1;
    add_header Cache-Control "no-store, no-cache, must-revalidate";
}

安全配置

安全头

添加安全头可以增强网站安全性:

# 安全头
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

隐藏版本号

隐藏 Nginx 版本号可以减少攻击面:

server_tokens off;

常见问题

403 Forbidden 错误

如果出现 403 错误,检查以下几点:

  • 文件权限是否正确(通常需要 644 权限)
  • 目录权限是否正确(通常需要 755 权限)
  • Nginx 用户是否有权访问文件
# 设置正确的权限
chmod 644 /www/wwwroot/hefei.space/index.html
chmod 755 /www/wwwroot/hefei.space

配置测试

在重新加载配置前,先测试配置是否正确:

# 测试配置
nginx -t

# 重新加载配置
nginx -s reload