前端相对路径的逻辑主要涉及 基础路径(Base Path) 的概念。针对你的需求,有几种解决方案:

1. HTML <base> 标签方案

在你的 HTML 文件的 <head> 部分添加:

<head>
  <base href="/app/">
</head>

这样所有相对路径都会以 /app/ 为基础:

  • src="xxx" → 实际请求 /app/xxx
  • href="yyy" → 实际请求 /app/yyy

2. 构建工具配置

Webpack 配置

module.exports = {
  output: {
    publicPath: '/app/'
  }
};

Vite 配置

// vite.config.js
export default {
  base: '/app/'
}

Create React App

// package.json
{
  "homepage": "/app"
}

3. 服务器配置

Nginx 配置

location /app/ {
    alias /path/to/your/static/files/;
    try_files $uri $uri/ /app/index.html;
}

Apache 配置

<Directory "/path/to/your/app">
    RewriteEngine On
    RewriteBase /app/
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /app/index.html [L]
</Directory>

4. JavaScript 动态处理

// 获取当前基础路径
const basePath = '/app/';
 
// 处理资源路径
function getAssetPath(path) {
  return basePath + path.replace(/^\//, '');
}
 
// 使用示例
const imageSrc = getAssetPath('images/logo.png'); // 结果: /app/images/logo.png

5. CSS 中的相对路径

/* 如果设置了 base href="/app/" */
.background {
  background-image: url('images/bg.jpg'); /* 实际路径: /app/images/bg.jpg */
}
 
/* 或者直接使用绝对路径 */
.background {
  background-image: url('/app/images/bg.jpg');
}

推荐方案

对于你的情况,我推荐:

  1. 开发阶段 :使用构建工具的 basepublicPath 配置
  2. 部署阶段 :结合 HTML <base> 标签和服务器配置

这样可以确保所有静态资源(CSS、JS、图片等)都能正确加载,路径都会自动添加 /app/ 前缀。

你现在使用的是什么前端框架或构建工具?我可以提供更具体的配置建议。