简体   繁体   English

允许 Cors 与 apache 网络服务器上的 .htaccess 文件

[英]Allow Cors with .htaccess file on apache webserver

Can I use a .htaccess file on my folder where I upload my file to my website, to allow cors?我可以在我将文件上传到我的网站的文件夹中使用 .htaccess 文件,以允许 cors 吗? I try to use this code here in my .htaccess file:我尝试在我的 .htaccess 文件中使用此代码:

Access-Control-Allow-Origin: *

But this don't work.但这不起作用。 Do I have to add something or do something else?我必须添加一些东西还是做其他事情?

Add the following lines in your .htaccess file will solve your problem.在 .htaccess 文件中添加以下行将解决您的问题。

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

You can also resolve cross origin from the index.php file itself.您还可以从 index.php 文件本身解析交叉源。 So, there you don't need to make changes in .htaccess file.因此,您无需在 .htaccess 文件中进行更改。 Try the following code in your index file.在您的索引文件中尝试以下代码。

// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
    // should do a check here to match $_SERVER['HTTP_ORIGIN'] to a whitelist of safe domains
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");         

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Apache允许所有站点使用.htaccess文件 - Apache allow all sites to use .htaccess file Apache .htaccess:仅限localhost上的CORS * - Apache .htaccess: CORS * on localhost only 如何使用apache2为Linux Web服务器上的音频文件设置CORS访问权限? - How can I set CORS access for an audio file on my Linux webserver with apache2? Apache、.htaccess - 禁止直接访问文件,但允许重写到 go - Apache, .htaccess - Forbidding direct access to a file, but allow rewrites to go there TYPO3 9:默认htaccess文件无法像Apache Web服务器的vhost中的include一样工作 - TYPO3 9: Default htaccess-file not working as include in vhost of apache webserver 如何在 .htaccess 文件的帮助下拒绝直接访问存储在网络服务器上的 python 文件,但仍然允许从另一个文件访问它? - How can I deny direct access to a python file stored on a webserver with help of an .htaccess file but still allow access to it from another file? 为什么我的 Apache2 .htaccess 文件 CORS 标头导致 500 内部服务器错误? - Why is my Apache2 .htaccess file CORS header causing a 500 internal server error? 在 Apache 中使用 .htaccess 文件 - Using .htaccess file in Apache Apache htaccess 重定向文件 - Apache htaccess redirect file .htaccess文件无法被Apache识别 - .htaccess file is not recognized by Apache
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM