需求分析
当前存在两个独立部分:前端静态资源(iscweb)和后端服务(fs-isc,端口6002)。需要通过Nginx配置实现本地通过静态页面访问后端服务,解决跨域问题并统一入口。
Nginx配置方案
以下是一个完整的Nginx配置文件示例,假设静态资源存放在F:/git/kcop-zh-project/aoi/iscweb目录,后端服务运行在http://x.x.x.x:6002
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
server {
listen 8081;
server_name localhost;
location ^~ /iscweb {
if ($uri ~* \.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css|tff|woff|swf|svg|xls|xlsx|json)$) {
rewrite ^\/iscweb\/(.*)$ /$1;
#本地的 jq-web
#root F:/git/kcop-zh-project/kcop-zh/cop/cop/web;
root F:/git/kcop-zh-project/aoi/iscweb;
break;
}
# 对于前端路由(如Vue/React的单页应用)
try_files $uri $uri/ /iscweb/index.html;
}
# 代理后台API接口 - 根据实际接口路径配置
location ^~ /api/fs-isc/ {
proxy_pass http://x.x.x.x:6002/fs-isc/;
# 设置必要的代理头
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
# 超时设置
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
include servers/*;
}
关键配置说明
- 静态资源路由 :
location ^~ /iscweb指向前端资源目录,try_files确保单页应用路由正常 - API代理 :
location ^~ /api/fs-isc/将所有以/api/fs-isc开头的请求转发到后端服务 - 头部信息 :通过
proxy_set_header传递必要的请求头信息
本地开发调整
前端代码中需要将API请求地址改为相对路径(如/api/xxx),避免硬编码端口。例如Axios实例配置:
const api = axios.create({
baseURL: 'api/fs-isc',
timeout: 5000
});
验证与测试
- 启动Nginx服务
- 访问http://localhost:8081/iscweb/basic/pages/login.html?theme=smart-blue应显示前端页面
- 检查前端发起的API请求是否被正确代理到
http://localhost:6002 - 通过浏览器开发者工具观察网络请求,确认无跨域错误
常见问题处理
- 404错误:检查静态资源路径是否正确,或后端服务是否运行
- 代理失败 :确认Nginx配置中
proxy_pass的地址与后端服务地址一致 - 缓存问题 :开发时可添加
proxy_set_header Cache-Control "no-cache"禁用缓存
进阶配置建议
如需HTTPS支持或更复杂的路由规则,可扩展配置:
location ~ ^/(auth|admin) {
proxy_pass http://localhost:6002;
# 其他自定义规则...
}
此配置实现了前后端分离架构下的本地开发环境整合,同时为生产环境部署提供了基础模板。