树莓派Express+Nginx+serve-favicon站点无法加载网站图标问题
树莓派Nginx反向代理Express环境下Favicon无法显示问题
我跟着Fireship教程在树莓派上搭建了Nginx反向代理Express的静态HTTP服务器,尝试添加网站图标(favicon)但始终无法正常显示。作为Nginx/Express新手,大概率犯了基础错误,目前已完成以下排查:
- 已安装
serve-favicon依赖; - 用
file favicon.ico命令测试过文件,确认文件正常; - favicon.ico位于项目根目录。
相关配置
Express - server.js
const { readFileSync, writeFileSync } = require('fs') const express = require('express') const app = express() const path = require('path') app.listen(5000, () => console.log('http://localhost:5000/')) const favicon = require('serve-favicon') app.use(favicon(path.join(__dirname,'favicon.ico')));
HTML(已尝试添加/移除该标签)
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
Nginx - default配置
server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name _; location / { proxy_pass http://localhost:5000; try_files $uri $uri/ =404; } location = /favicon.ico { try_files $uri =204; log_not_found off; access_log off; } }
添加location = /favicon.ico {...}配置后,不再出现404错误,但图标仍未加载。我有两个疑问:
- 已有
location /配置,为何无法加载该文件? - proxy_pass是否带来了未知的问题?
编辑1:尝试了以下配置,但仍无效果:
server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name _; location / { try_files $uri $uri/ =404; proxy_pass http://localhost:5000; } location = /favicon.ico { alias /var/www/html/favicon.ico; } }
编辑2:在以下配置下,本地访问http://localhost:5000能看到favicon.ico,但通过网络地址和外部站点地址访问时无法显示:
/etc/nginx/sites-available/default
location = /favicon.ico { alias /var/www/html/favicon.ico; }
server.js
app.use("/favicon.ico", express.static("./favicon.ico"));
编辑3:不知为何,使用Express方式突然恢复正常:
- 通过Express提供图标文件;
- Nginx对该路径做proxy_pass代理(似乎必须显式配置路由才能生效);
- HTML中的图标引用标签似乎并非必需。
内容的提问来源于stack exchange,提问作者HotSauceCoconuts
相关产品推荐
相关产品推荐

