配置Nginx作为静态资源服务器是一个常见且高效的做法。以下是详细的配置步骤和说明:
/etc/nginx/conf.d/static.conf
或/etc/nginx/sites-available/
目录下)server {
listen 80;
server_name static.example.com; # 替换为你的域名或IP
# 静态文件根目录
root /path/to/your/static/files;
# 默认文件索引
index index.html;
# 启用自动目录列表(可选)
autoindex off;
location / {
try_files $uri $uri/ =404;
}
# 静态资源缓存设置
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
}
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_proxied any;
location ~* \.(jpg|jpeg|png|gif|ico)$ {
valid_referers none blocked yourdomain.com *.yourdomain.com;
if ($invalid_referer) {
return 403;
}
}
location ~* \.(eot|ttf|woff|woff2)$ {
add_header Access-Control-Allow-Origin *;
}
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
sendfile on;
tcp_nopush on;
tcp_nodelay on;
worker_processes auto; # 自动根据CPU核心数设置
events {
worker_connections 1024; # 每个工作进程的最大连接数
}
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
server_tokens off;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
user nginx;
worker_processes auto;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
server {
listen 80;
server_name static.example.com;
root /var/www/static;
index index.html;
access_log /var/log/nginx/static.access.log;
error_log /var/log/nginx/static.error.log;
location / {
try_files $uri $uri/ =404;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
server_tokens off;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
}
}
sudo nginx -t
sudo systemctl reload nginx
# 或
sudo service nginx reload
sudo chown -R nginx:nginx /path/to/your/static/files
sudo chmod -R 755 /path/to/your/static/files
这样配置后,Nginx就能高效地作为静态资源服务器运行了。根据实际需求,你可以调整缓存时间、压缩级别等参数。