大网数据广告活动
网站运营与故障问答

can apache both redirect and set CORS headers?

· 52CE 我爱测

I encountered the following browser console message, using apache to redirect from http to https XMLHttpRequest cannot load http://xxx . Redirect from ' http://xxx ' to ' https://xxx ' has been blocked by CORS policy: No 'Access-…

问题原文

原帖链接 · rogerdpack · CC BY-SA 3.0

I encountered the following browser console message, using apache to redirect from http to https

XMLHttpRequest cannot load http://xxx. Redirect from 'http://xxx' to 'https://xxx' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://current_page' is therefore not allowed access.

Even though https://xxx has correct CORS headers set.

Turns out that apache's "redirect all" directive:

<VirtualHost *:80>
   ServerName servername
   Redirect permanent / https://servername/
</VirtualHost>

apparently needs to include a CORS header or the redirect itself will be rejected by web browser.

Is it possible to have apache's "redirect permanent" also include CORS headers?

I tried this, from random googling:

<VirtualHost *:80>
   ServerName xxx
   # hope this preserves url's for the auto redir :)
   Header always set Access-Control-Allow-Origin "*"
   Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
   Header always set Access-Control-Max-Age "1000"
   Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
   Redirect permanent / https://xxx/
</VirtualHost>

Or any other work around here?

已采纳解答

原帖链接 · MrWhite · CC BY-SA 3.0

Setting the required HTTP response headers before the redirect (which sets the HTTP status and Location headers) should work.

However, you will need to make sure that all local caches are cleared before testing. The earlier permanent redirect (that didn't include the CORS headers) will have been cached, so any new requests will not hit your server and see the update until the cache is cleared.

The local cache would seem to have been the problem in this instance.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2016-11-11)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。