Nginx是一个高性能的HTTP和反向代理服务器,非常适合用来提供静态资源服务。以下是使用Nginx代理实现静态资源访问的详细步骤:
server {
listen 80;
server_name example.com;
location /static/ {
alias /path/to/your/static/files/;
# 启用目录列表(可选)
autoindex on;
# 设置缓存头
expires 30d;
add_header Cache-Control "public";
}
}
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;
}
如果需要允许跨域访问静态资源:
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';
}
location /static/ {
alias /path/to/static/files/;
# 禁止访问隐藏文件
location ~ /\. {
deny all;
}
# 禁止执行PHP等脚本文件
location ~ \.php$ {
deny all;
}
}
假设你的静态资源存放在/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;
}
}
测试Nginx配置是否正确:
nginx -t
重新加载Nginx配置:
nginx -s reload
访问静态资源:
index
指令,访问http://static.example.com
会显示index文件http://static.example.com/image.jpg
通过以上配置,Nginx可以高效地提供静态资源服务,并具备良好的性能和安全性。