server {
listen 80;
server_name example.com;
# 图片路径配置
location /images/ {
root /var/www/static;
# 启用目录列表(可选)
# autoindex on;
# 设置缓存头
expires 30d;
access_log off;
# 防止目录遍历
location ~ \.\. {
deny all;
return 403;
}
}
}
server {
listen 80;
server_name example.com;
# HTML静态页面配置
location / {
root /var/www/html;
index index.html index.htm;
# 启用try_files,优先匹配存在的文件
try_files $uri $uri/ =404;
}
}
server {
location /static/ {
alias /path/to/static/files/;
expires max;
add_header Cache-Control public;
}
location /uploads/ {
alias /path/to/uploaded/files/;
# 上传目录通常不缓存
expires off;
}
}
# 在http块中添加
http {
# 开启sendfile
sendfile on;
# 优化TCP数据包发送
tcp_nopush on;
# 保持连接超时时间
keepalive_timeout 65;
# 开启gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# 静态资源缓存
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
# 防止热链接
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403;
}
# 禁止执行PHP等脚本
location ~ \.php$ {
deny all;
}
}
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
gzip on;
gzip_disable "msie6";
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
location /images/ {
alias /var/www/images/;
expires 30d;
access_log off;
# 图片防盗链
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403;
}
}
location /static/ {
alias /var/www/static/;
expires max;
add_header Cache-Control public;
}
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
}
}
403 Forbidden错误
chmod -R 755 /path/to/directory
chown -R www-data:www-data /path/to/directory
404 Not Found错误
性能优化建议
路径匹配优先级
location = /path
location ^~ /path
location ~ \.php$
location /
通过以上配置,您可以高效地提供静态资源服务,同时确保安全性和性能优化。