You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Spring结合CloudFlare配置SSL/TLS后Axios请求失败求助

解决CloudFlare环境下前后端HTTPS通信问题

问题根源

你的请求实际被转发到了服务器IP的8443端口,而非通过域名isakgo.com访问——这说明前端请求没有经过Nginx代理,直接访问了后端服务:

  • 用CloudFlare Origin证书时,该证书仅被CloudFlare信任,浏览器不认可,所以报ERR_CERT_AUTHORITY_INVALID
  • 用Let's Encrypt证书时,证书的通用名称(CN)是域名isakgo.com,而非服务器IP,所以访问IP:8443时报ERR_CERT_COMMON_NAME_INVALID

解决方案

1. 配置Nginx反向代理后端接口

修改Nginx的前端站点配置,添加/api路径的反向代理规则,让所有API请求通过Nginx转发到Spring后端(推荐让后端用HTTP端口如8080,避免重复配置HTTPS):

server {
    listen 443 ssl;
    server_name isakgo.com;

    # CloudFlare Origin证书配置
    ssl_certificate /path/to/cloudflare-origin-cert.pem;
    ssl_certificate_key /path/to/cloudflare-origin-key.pem;

    # 前端静态文件路径
    root /path/to/react/build;
    index index.html;

    # 处理前端路由(React单页应用)
    location / {
        try_files $uri $uri/ /index.html;
    }

    # 反向代理API请求到Spring后端
    location /api {
        proxy_pass http://localhost:8080; # 后端HTTP端口,无需配置HTTPS
        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;
    }
}

# 强制HTTP转HTTPS
server {
    listen 80;
    server_name isakgo.com;
    return 301 https://$host$request_uri;
}

2. 调整Spring后端配置(可选但推荐)

  • 关闭Spring的8443 HTTPS端口,仅开启8080 HTTP端口
  • 添加配置,让后端仅接受来自Nginx的请求(增强安全):
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest().permitAll()
            .and().csrf().disable();
        // 仅允许本地Nginx访问
        http.requestMatcher(new RequestHeaderRequestMatcher("X-Forwarded-Proto"));
    }
}

3. 确保Axios请求配置正确

检查前端Axios的baseURL设置,确保请求的是域名而非IP:

// 在Axios全局配置中设置
axios.defaults.baseURL = "https://isakgo.com";

// 或者单个请求使用相对路径
await axios.post("/api/processLogin"); // 无需写全域名

4. 验证CloudFlare SSL配置

保持CloudFlare的SSL/TLS模式为Full(strict),开启Always Use HTTPS——此模式要求Nginx使用CloudFlare信任的证书(Origin证书或Let's Encrypt证书均可),CloudFlare会负责对外的HTTPS加密。

关键说明

无需为Spring后端配置HTTPS,因为Nginx到后端的通信在服务器内部进行,用HTTP足够安全;所有对外请求通过Nginx的HTTPS端口处理,CloudFlare负责与客户端的加密通信,这样既避免了证书不匹配问题,也简化了配置。

内容的提问来源于stack exchange,提问作者na_sacc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 06:15:00