【发布时间】:2021-01-14 00:57:27
【问题描述】:
我们在一台服务器上有两个站点。我们创建了一个 rest api,api 后端代码位于 Site1.com。 在第二个站点上,有一个前端向第一个站点的 API 发送请求 但是我们遇到错误 405 和这个错误: 跨域请求被阻止:同源策略不允许读取位于http://site1.com/t.php 的远程资源。 (原因:CORS 预检响应未成功)
.htaccess 在 Site1.com 上:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
</IfModule>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
API 代码 Site1.com/t.php:
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
echo json_encode($_POST, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
控制台浏览器:
OPTIONS
scheme : http
host : Site1.com
filename : /t.php
Address : ***.8.173.***:80
Status405
Method Not Allowed
VersionHTTP/1.1
Transferred431 B (0 B size)
Access-Control-Allow-Headers : x-requested-with, Content-Type, origin, authorization, accept, client-security-token
Access-Control-Allow-Methods : POST, GET, OPTIONS, DELETE, PUT
Access-Control-Allow-Origin : *
Allow :
Connection
Keep-Alive
Content-Length
230
Content-Type
text/html; charset=iso-8859-1
Date
Mon, 28 Sep 2020 12:19:28 GMT
Keep-Alive
timeout=2, max=99
Server
Apache/2
Accept
*/*
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Access-Control-Request-Headers
content-type
Access-Control-Request-Method
POST
Connection
keep-alive
Host
Site2.com
Origin
http://Site2.com
Referer
http://Site2.com/
User-Agent
Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0
【问题讨论】:
-
您的
Site1.com目前根本不愿意回答 OPTIONS 请求,因此您首先需要让它这样做。 -
您想通过
RewriteCond %{REQUEST_METHOD} OPTIONS实现什么目标? RewriteCond 会影响直接跟随的 RewriteRule,但您没有立即遵循此规则。可以肯定的是,以目前的形式,这将一事无成。 -
@04FS
RewriteCond指令仍然适用于以下RewriteRule指令,即使它不是立即跟随。但是,在这种情况下,这严格来说是一个错误,因为应该无条件地处理下面的RewriteRule。 (尽管这实际上不会导致“错误”,但效率会降低。) -
旁白: 规范的 www 到非 www 重定向也在错误的位置 - 这应该靠近配置的顶部,否则它永远不会被处理对于通过您的前端控制器路由的任何 URL。 (你没有使用 HTTPS 吗?)
标签: php apache .htaccess vue.js centos