如何配置Apache实现HTTPS下API访问 解决net::ERR_SSL_PROTOCOL_ERROR错误
问题原因
你当前的配置存在3个核心错误:
- 443端口虚拟主机的反向代理规则配置错误,将所有根路径请求都转发到了API接口,会导致前端静态资源无法访问,同时路径拼接错误导致API请求路径多出层级
- 80端口虚拟主机错误配置了SSL证书参数,未配置HTTP强制跳HTTPS逻辑
- 需确认API目录拼写是否一致(文件夹结构中为
rest-api-authentification,API虚拟主机配置中为rest-api-authentication,拼写不一致会导致404)
解决步骤
1. 开启必要Apache模块
执行命令开启代理相关模块:
a2enmod proxy proxy_http systemctl restart apache2
2. 修正80端口虚拟主机配置(domain@react.conf)
删除原配置中的SSL相关参数,改为HTTP强制跳转HTTPS:
<VirtualHost *:80> DocumentRoot "/mnt/example/frontend/build" ServerName xxxx.ca ServerAlias www.xxxx.ca <Directory "/mnt/example/frontend/build"> AllowOverride All Require all granted </Directory> # 重定向所有HTTP请求到HTTPS RewriteEngine On RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L] </VirtualHost>
3. 修正443端口虚拟主机的代理配置(domain@react-le-ssl.conf)
将原全局代理规则改为仅匹配/api前缀的请求,修正路径拼接逻辑:
<IfModule mod_ssl.c> <VirtualHost *:443> DocumentRoot "/mnt/example/frontend/build" ServerName xxxx.ca ServerAlias www.xxxx.ca <Directory "/mnt/example/frontend/build"> AllowOverride All Require all granted </Directory> # 修正后的代理配置 ProxyRequests off ProxyPreserveHost on # 仅匹配/api开头的请求转发到8080端口的API服务 ProxyPass /api/ http://127.0.0.1:8080/api/ ProxyPassReverse /api/ http://127.0.0.1:8080/api/ SSLCertificateFile /etc/letsencrypt/live/xxxx.ca/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/xxxx.ca/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> </IfModule>
4. 确认API虚拟主机配置(domain@api.conf)
检查目录拼写和文件夹结构一致,保持如下配置即可:
<VirtualHost *:8080> DocumentRoot "/mnt/example/rest-api-authentification" # 注意和实际文件夹名一致 ServerName xxxx.ca ServerAlias www.xxxx.ca <Directory "/mnt/example/rest-api-authentification"> AllowOverride None Require all granted Options Indexes FollowSymLinks </Directory> </VirtualHost>
5. 生效配置
执行命令测试配置语法无误后重载配置:
apache2ctl configtest systemctl reload apache2
关于SSL证书的疑问
不需要为8080端口的API单独申请SSL证书。HTTPS的加密解密逻辑完全由443端口的前端虚拟主机处理,代理到本地8080端口的请求属于服务器内部请求,不需要加密,也不需要配置SSL证书。
内容的提问来源于stack exchange,提问作者Vaitea Doppia
相关产品推荐
相关产品推荐

