在Linux服务器上使用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
编辑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; # 可选:启用目录列表
}
# 其他配置...
}
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";
}
}
确保Nginx用户(通常是www-data
或nginx
)有权限访问静态资源目录:
sudo chown -R www-data:www-data /path/to/your/static/files
sudo chmod -R 755 /path/to/your/static/files
# 测试配置是否正确
sudo nginx -t
# 重启Nginx使配置生效
sudo systemctl restart nginx
在浏览器中访问:
http://your_server_ip/static/
或者使用curl测试:
curl http://localhost/static/
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
location ~* \.(jpg|jpeg|png|gif)$ {
valid_referers none blocked yourdomain.com *.yourdomain.com;
if ($invalid_referer) {
return 403;
}
}
location /private/ {
alias /path/to/private/files/;
allow 192.168.1.0/24;
deny all;
}
通过以上配置,您可以在Linux服务器上使用Nginx高效地提供静态资源服务。