这种需求常见于单页应用(SPA)的前端路由配置,目的是将所有非API请求都重定向到应用的入口文件(index.html),让前端路由来处理URL路径,同时保留对后端API的访问。
server {
listen 80;
server_name yourdomain.com;
root /path/to/your/app;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
location /api/ {
# 这里配置你的API后端处理
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
<VirtualHost *:80>
ServerName yourdomain.com
DocumentRoot /path/to/your/app
<Directory "/path/to/your/app">
RewriteEngine On
RewriteBase /
# 排除API请求
RewriteCond %{REQUEST_URI} !^/api/
# 如果请求的不是现有文件或目录
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# 重定向到index.html
RewriteRule ^ index.html [L]
</Directory>
# API处理
<Location "/api/">
ProxyPass http://backend/
ProxyPassReverse http://backend/
</Location>
</VirtualHost>
const express = require('express');
const path = require('path');
const app = express();
// 静态文件服务
app.use(express.static(path.join(__dirname, 'public')));
// API路由
app.use('/api', require('./api'));
// 其他所有请求重定向到index.html
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
问题1:刷新页面后出现404错误
问题2:API请求也被重定向到index.html
location /api/
块问题3:静态资源加载失败
try_files
或Apache的RewriteCond %{REQUEST_FILENAME} !-f
这些配置可以确保你的单页应用能够正确处理前端路由,同时保留对后端API的访问能力。
没有搜到相关的文章