IIS环境下实现Vue前端与ASP.NET API部署在同一域名的方法
实现方案
通过IIS反向代理+前端请求路径调整即可实现同域名访问API,具体操作步骤如下:
前置依赖配置
- 确认Windows Server的IIS已安装两个必需组件:
- URL Rewrite模块(你当前已在使用该模块配置规则,通常已预装)
- Application Request Routing(简称ARR)模块,是IIS实现反向代理转发的核心依赖
- 组件安装完成后打开IIS管理器,选中服务器根节点,找到「Application Request Routing Cache」功能,点击右侧操作栏的「Server Proxy Settings」,勾选Enable proxy选项后保存,开启全局代理能力。
修改站点web.config规则
IIS重写规则按从上到下的优先级匹配,需要把API路径的转发规则放在最靠前位置,避免被前端路由兜底规则、域名重定向规则拦截。修改后的完整配置如下:
<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <!-- 新增:API路径反向代理规则,优先级最高 --> <rule name="ReverseProxy to API Service" stopProcessing="true"> <match url="^api/(.*)" /> <action type="Rewrite" url="https://api.example.com/{R:0}" /> <serverVariables> <!-- 可选:后端如果校验Host头,保留该项配置即可 --> <set name="HTTP_HOST" value="api.example.com" /> </serverVariables> </rule> <!-- 原有规则:根域名跳转到www子域名,已修正原配置里写死的domain.com占位符 --> <rule name="Redirect to www" stopProcessing="true"> <match url="(.*)" /> <conditions trackAllCaptures="false"> <add input="{HTTP_HOST}" pattern="^example.com$" /> </conditions> <action type="Redirect" url="{MapProtocol:{HTTPS}}://www.example.com/{R:1}" /> </rule> <!-- 原有规则:Vue History模式路由兜底 --> <rule name="Handle History Mode and custom 404/500" 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> <rewriteMaps> <rewriteMap name="MapProtocol"> <add key="on" value="https" /> <add key="off" value="http" /> </rewriteMap> </rewriteMaps> </rewrite> <tracing> <traceFailedRequests> <clear /> </traceFailedRequests> </tracing> </system.webServer> <system.web> <compilation tempDirectory="C:\Inetpub\vhosts\example.com\tmp" /> </system.web> </configuration>
调整Vue 2.0项目配置
- 将项目中API请求的baseURL从原绝对地址
https://api.example.com改为相对路径/api,生产环境发起请求时会自动请求当前域名下的/api/xxx路径,触发反向代理规则。 - 本地开发环境可在项目根目录的
vue.config.js中配置代理,不影响本地调试:
// vue.config.js module.exports = { devServer: { proxy: { '/api': { target: 'https://api.example.com', // 本地调试对接的API地址 changeOrigin: true } } } }
验证注意事项
- 配置生效后同域名请求不存在跨域问题,可按需移除后端原来配置的跨域允许规则;如果后端接口有签名校验、来源校验逻辑,保留配置中HTTP_HOST转发规则即可。
- 配置更新后回收对应站点的应用程序池,清除浏览器缓存后再测试接口连通性。
内容的提问来源于stack exchange,提问作者Gonçalo Bastos
相关产品推荐
相关产品推荐

