Nginx 是一个高性能的 HTTP 和反向代理服务器,非常适合用于静态资源的服务。下面我将详细介绍如何配置 Nginx 来访问图片路径和 HTML 静态页面。
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html;
}
location /images/ {
root /var/www;
autoindex on; # 可选,开启目录列表
}
}
这个配置中:
- /
路径指向 /var/www/html
目录,会默认查找 index.html
- /images/
路径指向 /var/www/images
目录
server {
listen 80;
server_name example.com;
# 主目录配置
root /var/www;
# 默认首页
index index.html index.htm;
# 静态资源缓存设置
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
access_log off;
}
# 图片路径配置
location /images/ {
alias /var/www/images/;
# 或者使用 root
# root /var/www;
# 开启目录列表(可选)
autoindex on;
# 图片缓存设置
expires 7d;
}
# HTML页面配置
location / {
try_files $uri $uri/ /index.html;
}
# 防止访问隐藏文件
location ~ /\. {
deny all;
}
}
root:
location /images/ {
root /var/www;
}
/images/logo.png
会映射到 /var/www/images/logo.png
alias:
location /images/ {
alias /var/www/images/;
}
/images/logo.png
会直接映射到 /var/www/images/logo.png
/
结尾try_files
: 尝试按顺序查找文件,直到找到为止autoindex
: 是否允许目录列表expires
: 设置缓存时间add_header
: 添加响应头access_log off
: 关闭访问日志(对静态资源常用)server {
listen 80;
server_name img.example.com;
root /data/images;
location / {
autoindex off;
expires 30d;
access_log off;
}
# 防止盗链
location ~* \.(jpg|jpeg|png|gif)$ {
valid_referers none blocked example.com *.example.com;
if ($invalid_referer) {
return 403;
}
}
}
server {
listen 80;
server_name www.example.com;
root /var/www/example;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
# 静态资源缓存
location ~* \.(?:css|js|jpg|jpeg|gif|png|ico|svg|woff2)$ {
expires 365d;
access_log off;
add_header Cache-Control "public";
}
# 禁止访问 .htaccess 等隐藏文件
location ~ /\. {
deny all;
}
}
403 Forbidden 错误:
chmod -R 755 /var/www
chown -R nginx:nginx /var/www
setenforce 0
(临时关闭) 或配置正确的安全上下文404 Not Found 错误:
图片无法显示:
性能优化建议:
配置完成后,记得测试并重新加载 Nginx:
sudo nginx -t # 测试配置
sudo systemctl reload nginx # 重新加载配置
希望这些配置示例和说明能帮助你正确设置 Nginx 来服务图片和 HTML 静态页面。