一、架构说明
用户访问 → Nginx(前端静态文件+API代理) → IIS(托管Vue应用) → 后端服务
二、核心配置方案
方案1:Nginx同时代理前端和后端(推荐)
Nginx配置(nginx.conf):
# 前端Vue应用(通过IIS托管)
server {
listen 80;
server_name your-domain.com;
# 静态资源
location / {
proxy_pass http://localhost:8080; # IIS端口
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;
}
# API代理
location /api/ {
proxy_pass http://backend-server:3000/; # 后端服务地址
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 解决跨域
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
# 处理OPTIONS预检请求
if ($request_method = 'OPTIONS') {
return 204;
}
}
}
方案2:前端配置代理(开发/生产统一)
Vue项目配置(vue.config.js):
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://backend-server:3000',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
}
},
// 生产环境配置
publicPath: process.env.NODE_ENV === 'production' ? '/' : '/',
// 构建输出目录
outputDir: 'dist',
// 配置环境变量
configureWebpack: {
// 可在此配置全局变量
}
}
环境配置文件(.env.production):
VUE_APP_API_BASE_URL=/api
NODE_ENV=production
三、IIS配置步骤
1. 安装IIS功能
- Web服务器(IIS)
- 应用程序开发 → ASP.NET 4.7
- 管理工具 → IIS管理控制台
2. 安装URL重写模块
下载并安装:URL Rewrite Module
3. 配置Vue应用
web.config(放在Vue项目根目录):
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<!-- Vue Router History模式支持 -->
<rule name="Vue Routes" stopProcessing="true">
<match url=".*" />
<conditions logicalGrouping="MatchAll">
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="/" />
</rule>
</rules>
</rewrite>
<!-- 静态文件缓存 -->
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
</staticContent>
<!-- MIME类型 -->
<staticContent>
<remove fileExtension=".json" />
<mimeMap fileExtension=".json" mimeType="application/json" />
<remove fileExtension=".vue" />
<mimeMap fileExtension=".vue" mimeType="text/xml" />
</staticContent>
</system.webServer>
</configuration>
四、部署步骤
1. 构建Vue项目
npm run build
# 或
yarn build
2. 配置IIS站点
将
dist文件夹内容复制到IIS站点目录
创建应用程序池(.NET CLR版本:无托管代码)
添加网站,绑定到端口(如8080)
设置默认文档:index.html
3. 完整Nginx配置示例
# 全局配置
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
# 基础配置
include /etc/nginx/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 /var/log/nginx/access.log main;
# 优化参数
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# Gzip压缩
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# Vue应用服务器
upstream vue_app {
server 127.0.0.1:8080; # IIS
}
# 后端API服务器
upstream api_server {
server backend-server:3000; # 后端服务
# 可以配置多个后端服务器做负载均衡
# server backend-server2:3000;
}
# HTTP服务器配置
server {
listen 80;
server_name your-domain.com www.your-domain.com;
# 重定向到HTTPS
return 301 https://$server_name$request_uri;
}
# HTTPS服务器配置
server {
listen 443 ssl http2;
server_name your-domain.com www.your-domain.com;
# SSL证书配置
ssl_certificate /path/to/your-cert.pem;
ssl_certificate_key /path/to/your-key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
# 前端应用
location / {
proxy_pass http://vue_app;
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_read_timeout 60s;
proxy_send_timeout 60s;
# 禁用缓存,用于开发
# add_header Cache-Control "no-cache, no-store, must-revalidate";
}
# 静态资源单独处理
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
proxy_pass http://vue_app;
proxy_set_header Host $host;
# 启用缓存
expires 1y;
add_header Cache-Control "public, immutable";
}
# API接口代理
location /api/ {
proxy_pass http://api_server/;
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;
# 跨域配置
add_header Access-Control-Allow-Origin $http_origin always;
add_header Access-Control-Allow-Credentials true always;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header Access-Control-Allow-Headers 'Origin, X-Requested-With, Content-Type, Accept, Authorization' always;
# 处理预检请求
if ($request_method = 'OPTIONS') {
add_header Access-Control-Max-Age 1728000;
add_header Content-Type 'text/plain; charset=utf-8';
add_header Content-Length 0;
return 204;
}
# WebSocket支持(如果需要)
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
# 健康检查
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
}
}
五、Vue项目代码调整
1. API请求配置
// src/utils/request.js
import axios from 'axios';
const service = axios.create({
baseURL: process.env.VUE_APP_API_BASE_URL || '/api',
timeout: 15000
});
// 请求拦截器
service.interceptors.request.use(
config => {
// 添加token等
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
},
error => {
return Promise.reject(error);
}
);
// 响应拦截器
service.interceptors.response.use(
response => {
return response.data;
},
error => {
// 错误处理
return Promise.reject(error);
}
);
export default service;
2. 环境变量配置
// 在Vue组件中使用
const apiUrl = process.env.VUE_APP_API_BASE_URL;
六、优化建议
静态资源缓存:
- Vue打包的文件名带hash,可设置长期缓存
- 配置nginx的expires指令
负载均衡:
upstream backend {
server backend1:3000 weight=3;
server backend2:3000;
server backend3:3000 backup;
}
安全配置:
- 限制请求体大小
- 隐藏nginx版本信息
- 配置SSL/TLS
- 设置安全头部
性能监控:
- 启用nginx状态模块
- 配置日志分析
- 监控服务器资源
七、常见问题解决
404错误:
- 检查IIS URL重写规则
- 确认nginx代理路径正确
跨域问题:
- 确保nginx正确配置CORS头
- 检查后端服务是否允许跨域
静态资源加载失败:
- 检查publicPath配置
- 确认nginx正确代理静态资源
HTTPS重定向循环:
- 检查proxy_set_header配置
- 确认X-Forwarded-Proto正确传递
这种部署方式结合了IIS的稳定性和nginx的高性能代理能力,适合生产环境使用。