AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / server / 问题

问题[cors](server)

Martin Hope
serverNewbie
Asked: 2021-09-27 12:29:31 +0800 CST

“不允许 CORS 多源” - 使用 parse-server 和 apache2

  • 0

我使用 apache2 作为我的解析服务器的反向代理。为了允许跨域请求,我最初尝试设置:

Header always set Access-Control-Allow-Origin "*"

在 apache 配置文件中连同:

ProxyPass /parse/ http://localhost:1337/parse/
ProxyPassReverse /parse/ http://localhost:1337/parse/
RewriteEngine On
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

设置后,请求成功地从 apache 转发到我的解析服务器。但是现在我的 Webapp 抛出CORS Multiple Origin Not Allowed.

在我的浏览器的开发者控制台中,我可以看到这个 Access-Control-Allow-Origin 选项设置了两次。

在此处输入图像描述

我已经确认第二个实例是由于解析服务器而出现的。但是,我找不到阻止 parse-server 或 apache 在响应中设置此选项的方法。

我尝试将 apache 配置中的初始行更改为:

1.

Header always setifempty Access-Control-Allow-Origin "*"
Header always add Access-Control-Allow-Origin "*"
Header always add Access-Control-Allow-Origin "*"
Header always edit Access-Control-Allow-Origin "^$" "*"

这些尝试都没有改变任何东西。但是,删除Access-Control-Allow-Originapache 配置中的选项会阻止初始请求通过解析服务器,因此这不是一个选项。

我正在使用 apache2 版本2.4.29和 parse-server 4.10.3。

有谁知道让这个工作的方法?

reverse-proxy apache-2.4 apache2 parse-server cors
  • 2 个回答
  • 1858 Views
Martin Hope
delato468
Asked: 2021-08-11 02:33:17 +0800 CST

CORS 防止 js window.onerror 从子域报告信息

  • 0

为了记录 Javascript 错误,我设置了一个带有 window.onerror 的函数,它触发了一个 ajax 请求并通知我脚本错误。我从子域加载所有静态文件,如果主域之外的文件发生错误,CORS 似乎会因为泄漏而删除信息... https://developer.mozilla.org/en-US/docs/ Web/API/GlobalEventHandlers/onerror#notes

我试图通过像这样设置 Access-Control-Allow-Origin 来解决这个问题:

add_header Access-Control-Allow-Origin https://static.example.com;

但没有成功。

我的子域也带有主域的 Access-Control-Allow-Origin。

文件标题:

Request URL: https://www.example.com/de/kontaktformular.html
Request Method: GET
Status Code: 200 
Remote Address: XXX
Referrer Policy: strict-origin-when-cross-origin
access-control-allow-origin: https://static.example.com
cache-control: no-store, no-cache, must-revalidate
content-encoding: br
content-security-policy: ...
content-type: text/html; charset=UTF-8
date: Tue, 10 Aug 2021 10:21:35 GMT
expect-ct: enforce,max-age=30
expires: Thu, 19 Nov 1981 08:52:00 GMT
pragma: no-cache
referrer-policy: same-origin
server: nginx
strict-transport-security: max-age=15768000; includeSubDomains
vary: Accept-Encoding
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
:authority: www.example.com
:method: GET
:path: /de/kontaktformular.html
:scheme: https
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
accept-encoding: gzip, deflate, br
accept-language: de-IT,de;q=0.9,en-US;q=0.8,en;q=0.7,de-DE;q=0.6
cache-control: no-cache
cookie: __Host-PHPSESSID=k2284o6ejliq4t9113bicbv5tr; cookie_alert=1; cart=MjMtLC03OC0sLTF8fDU1LSwtMTI3LSwtMXx8NTUtLC0xMjgtLC0x
pragma: no-cache
referer: https://www.example.com/de/XXX.html
sec-ch-ua: "Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"
sec-ch-ua-mobile: ?0
sec-fetch-dest: document
sec-fetch-mode: navigate
sec-fetch-site: same-origin
sec-fetch-user: ?1
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36

来自子域的 Js 文件的标头:

Request URL: https://static.example.com/jquery_scripts.128.js
Request Method: GET
Status Code: 200 
Remote Address: XXX
Referrer Policy: same-origin
access-control-allow-origin: https://www.example.com
cache-control: public, max-age=31536000, s-maxage=31536000
content-encoding: gzip
content-type: text/javascript;charset=UTF-8
date: Tue, 10 Aug 2021 10:21:35 GMT
expires: Wed, 10 Aug 2022 10:21:35 GMT
last-modified: Tue, 10 Aug 2021 09:38:16 GMT
server: nginx
strict-transport-security: max-age=15768000; includeSubDomains
vary: Accept-Encoding
x-content-type-options: nosniff
:authority: static.example.com
:method: GET
:path: /jquery_scripts.128.js
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: de-IT,de;q=0.9,en-US;q=0.8,en;q=0.7,de-DE;q=0.6
cache-control: no-cache
pragma: no-cache
sec-ch-ua: "Chromium";v="92", " Not A;Brand";v="99", "Google Chrome";v="92"
sec-ch-ua-mobile: ?0
sec-fetch-dest: script
sec-fetch-mode: no-cors
sec-fetch-site: same-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36
javascript nginx http-headers cors
  • 1 个回答
  • 101 Views
Martin Hope
UncleBob
Asked: 2021-08-03 07:34:25 +0800 CST

AWS Cloudfront CORS 字体文件问题

  • 1

我有一个从 CloudFront 端点传送到浏览器的 Javascript 应用程序。应用程序的所有静态文件都托管在 S3 存储桶中。这涉及一大堆 javascript 和 css 文件,以及一些字体文件。

加载整个应用程序的 html 是由服务器生成和交付的,我们称该服务器为“https://my.domain.com”。

如前所述,这只是 html 文件。然后从指向存储桶作为其来源的云端端点下载所有静态内容。我们将这些称为 xxxx.cloudfront.net 和存储桶 my-bucket。

据我了解,几乎所有从生成的 html 到云端端点的请求都是 CORS 请求,因为 html 的来源是 my.domain.com,并且所有请求的文件显然都没有托管在该域上。

所以很自然,我去设置所有 CORS 的东西。首先,bucket 是完全公开的,它具有以下 CORS 策略:

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "GET"
        ],
        "AllowedOrigins": [
            "*",
        ],
        "ExposeHeaders": [],
        "MaxAgeSeconds": 3000
    }
]

这似乎对一切都有效……除了字体文件!我可能应该提到存储桶的文件夹结构。它有三个文件夹,生产、开发和通用。这些内容应该是不言自明的。Common 包含字体,以及一些 3rd 方 javascript 库。生产和开发包含各自环境的 js 和 css。

无论如何,除了字体文件之外,所有内容都会加载,我收到以下错误:

Access to font at 'https://xxxx.cloudfront.net/common/fonts/outline/budicon-classic.ttf?jdete2' from origin 'https://my.domain.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

让我感到非常奇怪的是,只有字体文件会有这个问题。公共文件夹中的其他文件似乎加载得很好,如果我只是将https://xxxx.cloudfront.net/common/fonts/outline/budicon-classic.ttf?jdete2粘贴到我的浏览器中,它可以工作。

唯一的区别似乎是这些文件不是从 html 加载的,而是通过 @font-face thingy 从 css 加载的。查看加载应用程序时浏览器生成的请求,我可以清楚地看到例如设置了 origin 标头,而不是用于请求 js 或 css 文件。Set-Fetch-Mode 设置为“cors”,而对于其他文件,它设置为“no-cors”。

无论如何,我试图在云端解决这个问题。首先,我在原始配置中添加了标题“Access-Control-Allow-Origin: *”。然后我为源添加了一个行为配置,以允许路径模式 *.

现在......好吧,现在我仍然有同样的问题,并且完全没有想法,虽然想知道为什么@font-face创建的请求与对javascript和css资源的请求相比形成如此不同,但是最重要的是,我到底能做些什么来加载他们血腥的字体?

amazon-s3 amazon-cloudfront css cors
  • 1 个回答
  • 909 Views
Martin Hope
Neijwiert
Asked: 2021-05-26 01:35:28 +0800 CST

IIS 反向代理 CORS 问题背后的 FoundryVTT 服务器

  • 0

我在 FreeNAS 监狱中有一个 FoundryVTT 服务器。我主要是按照这些说明来让它工作的。我有一个以前的问题,我解决了,现在对于 <= v0.7.9 可以正常工作。但是,>= v0.8 不再有效,当我通过 WAN 访问服务器时,我不断遇到与 CORS 相关的问题。我在日志记录和网页控制台(或通过提琴手)中唯一能看到的是 403 和正文:

{"error":"不允许跨域请求"}

错误页面图片

我已经联系了 FoundryVTT Discord,他们基本上说不应该更改任何与 CORS 相关的内容,并且我应该使用 IIS 管理器(v10.0.19041.1)以外的东西。

我试过的:

  • 已验证这是较新版本的实际问题。创建了一个新的 0.7.9。实例遵循相同的步骤,它工作正常。

  • 添加自定义标题,如下所示:

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers" />
        <add name="Access-Control-Allow-Methods" value="GET,HEAD,OPTIONS,POST,PUT" />
        <add name="Access-Control-Allow-Credentials" value="false" />
      </customHeaders>
    </httpProtocol>
    

    并使用它们的各种组合(例如指定www.myhost.com并允许凭据为真,* 允许标头/方法)

  • 应用出站重写规则:

    <rule name="Test1">
      <match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
      <action type="Rewrite" value="*" />
    </rule>
    <rule name="Test2">
      <match serverVariable="RESPONSE_Access_Control_Allow_Headers" pattern=".*" />
      <action type="Rewrite" value="*" />
    </rule>
    <rule name="Test3">
      <match serverVariable="RESPONSE_Access_Control_Allow_Methods" pattern=".*" />
      <action type="Rewrite" value="GET,HEAD,OPTIONS,POST,PUT,DELETE" />
    </rule>
    <rule name="Test4">
      <match serverVariable="RESPONSE_Access_Control_Allow_Credentials" pattern=".*" />
      <action type="Rewrite" value="false" />
    </rule>
    

    还尝试了各种组合,如前所述。

  • 安装了CORS 模块并尝试了各种方法,如下所示:

    <cors enabled="true" failUnlistedOrigins="false">
     <add origin="*" >
      <allowHeaders allowAllRequestedHeaders="true" />
      <allowMethods>
          <add method="GET" />
          <add method="POST" />
          <add method="PUT" />
          <add method="HEAD" />
          <add method="OPTIONS" />
          <add method="DELETE" />
      </allowMethods>
    </add>
    <add origin="https://www.myhost.com" allowCredentials="true" maxAge="120" >
      <allowHeaders allowAllRequestedHeaders="true" />
      <allowMethods>
          <add method="GET" />
          <add method="POST" />
          <add method="PUT" />
          <add method="HEAD" />
          <add method="OPTIONS" />
          <add method="DELETE" />
      </allowMethods>
     </add>
    </cors>
    

    在检查我在 IIS 中的应用程序是在 x86 还是 x64 模式下运行(它在 x64 模式下运行)之后,还特别尝试安装 CORS 模块的 x64 版本。

  • 重新启动一切。

似乎对我遇到的错误没有任何影响。在使用提琴手时,我可以看到如果我添加/更改标题,响应正在发生变化。下面是我在 IIS 中未应用任何 CORS 规则时捕获的 Fiddler 的图片。我设法看到一个管理员登录页面,但是一旦我提交密码,它就会给我错误。

提琴手捕获

iis reverse-proxy cors
  • 1 个回答
  • 437 Views
Martin Hope
XtevensChannel
Asked: 2021-01-12 15:49:02 +0800 CST

在 PHP 中启用 FPM 后 CORS 冲突

  • 1

在我的 Web 服务器上的 .htaccess 文件中,我设置了以下 CORS 标头:

Header set Access-Control-Allow-Origin "example.com"

在我从本地主机工作时经常调用的一个 PHP 脚本中,我设置了以下标头:

header("Access-Control-Allow-Origin: *");

直到昨天,当我为 PHP 打开 FPM 时,这一直对我有用。现在我收到以下错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.example.com/script.php. (Reason: CORS header 'Access-Control-Allow-Origin' does not match '*, example.com').

我只在从本地主机调用时收到该错误,而不是从网站调用时。我想知道既然.htaccess启用了 FPM,是否有办法通过 PHP 覆盖 CORS 标头。

php .htaccess php-fpm cors
  • 1 个回答
  • 887 Views
Martin Hope
glass
Asked: 2020-11-06 08:44:13 +0800 CST

Angular CORS 与 Nginx

  • 2

网上有几个关于同一主题的问题,但没有任何效果。

我有一个运行 Angular 应用程序的 serverXYZ、一个用于身份验证的后端 tomcat webapp、一个 nginx 服务器。Angular 应用程序在 4200 端口,tomcat 应用程序在 8080 端口。一切都在同一个主机上。

角度应用程序有一个 environment.ts 文件(注释字符串是我的测试之一,请参阅下面的 nginx conf):

export const environment = {
  production: false,
//  apiUrl: 'http://serverXYZ:444/api'
  apiUrl: 'http://localhost:8080/backend'
};

nginx 配置文件:

    server {
        listen 444;
    
            server_name serverXYZ;

            location / {
                    proxy_pass http://localhost:4200;
                    
                    //websocket
                    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;
                    proxy_pass_request_headers on;
                    proxy_http_version 1.0;
                    proxy_set_header Upgrade $http_upgrade;
                    proxy_set_header Connection "Upgrade";
                    proxy_read_timeout 120s;
            
                    if ($request_method = 'OPTIONS') {
                            add_header 'Access-Control-Allow-Origin' '*';
                            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
                            add_header 'Access-Control-Max-Age' 1728000;
                            add_header 'Content-Type' 'text/plain; charset=utf-8';
                            add_header 'Content-Length' 0;
                            return 204;
                    }
                    if ($request_method = 'POST') {
                            add_header 'Access-Control-Allow-Origin' '*';
                            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
                            add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
                    }
                    if ($request_method = 'GET') {
                            add_header 'Access-Control-Allow-Origin' '*';
                            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
                            add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
                    }
    
            }

            location /api {
                proxy_pass http://localhost:8080/backend;

                if ($request_method = 'OPTIONS') {
                        add_header 'Access-Control-Allow-Origin' '*';
                        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
                        add_header 'Access-Control-Max-Age' 1728000;
                        add_header 'Content-Type' 'text/plain; charset=utf-8';
                        add_header 'Content-Length' 0;
                        return 204;
                }
                if ($request_method = 'POST') {
                        add_header 'Access-Control-Allow-Origin' '*';
                        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
                        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
                }
                if ($request_method = 'GET') {
                        add_header 'Access-Control-Allow-Origin' '*';
                        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
                        add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
                        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
                }

           }
}

后端 tomcat 应用程序在其 web.xml 中有这个:

...
<!-- Tomcat built in CORS implementation -->
        <!--  https://tomcat.apache.org/tomcat-7.0-doc/config/filter.html -->
        <filter>
                <filter-name>CorsFilter</filter-name>
                <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
                <init-param>
                        <param-name>cors.allowed.headers</param-name>
                        <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization</param-value>
                </init-param>
                <init-param>
                    <param-name>cors.allowed.methods</param-name>
                    <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value>
                </init-param>
        </filter>
        <filter-mapping>
                <filter-name>CorsFilter</filter-name>
                <url-pattern>/*</url-pattern>
        </filter-mapping>
        <!-- End of built in CORS implementation -->
...

我使用我的电脑,打开浏览器,如果我连接到 http://serverXYZ:444,则使用描述的 conf 显示应用程序,但我在身份验证时收到 CORS 错误(CORS 请求失败)。相反,如果我在 environment.ts 中使用带有注释字符串的配置,则浏览器身份验证不会说 CORS,只是 403。当然,身份验证 api 已经过测试并且可以正常工作。

我一头雾水,怎么了?此外,使用 nginx 解决这个问题是我的首选方式,但不是强制性的。

编辑: 我添加了更多信息,我正在使用 "ng serve --disableHostCheck=true" 启动 Angular 应用程序。我不知道在这种情况下是否应该使用“--publicHost”选项或“--host 0.0.0.0”?

编辑 2: 我刚才看到的另一件事,Firefox 在 OPTIONS 请求上没有给我任何错误,只是在 POST 上出现 Cors。

nginx cors angular
  • 1 个回答
  • 5252 Views
Martin Hope
RtiOne Kkarkov
Asked: 2020-10-30 07:50:02 +0800 CST

Java服务器上Google App Engine中的CORS错误

  • 0

我有两个应用程序。

在 Firebase 上运行的前端(Angular)

在 App Engine 上运行的后端 Spring Boot (Java11)

尝试访问应用引擎中的任何端点时出现此错误"Access has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource"

有趣的是,在我的本地机器上一切正常。cors没有问题。所以,我猜问题出在应用引擎的配置或其他方面。

有人可以帮我解决这个问题吗?我已经花了很多时间试图修复它。已经阅读了很多 stackoverflow 类似的问题。上一篇:如何在 Spring Boot + Spring Security 应用中配置 CORS?

在谷歌文档中找不到任何有用的东西。

app.yaml 文件

runtime: java11
instance_class: F4
vpc_access_connector:
  name: projects/<project_id>/locations/<location>/connectors/<connectors_name>

这是我的配置文件:

CorsFilterConfig.java

@Configuration
public class CorsFilterConfig {
    
    @Value("${allowed-origin}")
    private String allowedOrigin;

    @Bean
    public FilterRegistrationBean<CorsFilter> simpleCorsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.setAllowedOrigins(Collections.singletonList(allowedOrigin));
        config.setAllowedMethods(Collections.singletonList("*"));
        config.setAllowedHeaders(Collections.singletonList("*"));
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }
}

allowedOrigin指向https://<firebase.domain>

安全配置.java

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .cors()
                .and()
                .csrf().disable()
                .authorizeRequests().anyRequest().authenticated()
                .and()
                .oauth2Login()
                .and()
                .oauth2ResourceServer().jwt();

端点示例

@RestController
@RequestMapping("/test")
@AllArgsConstructor
public class TestController {

    @GetMapping
    public String hello() {
        return "hello world";
    }
}

我猜您不能使用 app.yaml 来控制动态处理程序的 HTTP 标头。仅适用于静态内容

这就是为什么此配置无法部署并出现此错误的原因 "Unexpected attribute "http_headers" for mapping type script."

runtime: java11
instance_class: F4
vpc_access_connector:
  name: projects/<project_id>/locations/<location>/connectors/<connectors_name>
handlers:
  - url: /.*
    script: auto
    http_headers:
      Access-Control-Allow-Origin: *
java google-app-engine springboot cors
  • 3 个回答
  • 1500 Views
Martin Hope
Ben Davis
Asked: 2020-04-09 13:01:34 +0800 CST

使用 POST 请求时,Access-Control-Allow-Origin 标头不包含在响应中

  • 0

我的 nginx 配置中有以下内容:

location / {
    # CORS
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST' always;

    proxy_pass http://localhost:8080/guacamole/;  # systemd: tomcat9
    proxy_buffering off;
    proxy_http_version 1.1;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $http_connection;
    proxy_cookie_path /guacamole/ /;
    access_log off;
}

当我向服务器发送POST请求时,Access-Control-Allow-Origin响应中不存在标头。但是,当我发送GET请求时。任何想法为什么?

nginx cors
  • 1 个回答
  • 321 Views
Martin Hope
ChrisMatthewsNZ
Asked: 2017-02-17 11:33:17 +0800 CST

如何在同一个conf中同时添加CORS标头和浏览器过期标头

  • 1

我需要在 nginx 中添加两个过期标头并允许 cors

如果我添加

location ~*  \.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf|x-html|css|xml|js|woff|woff2|ttf|svg|eot)$ {
expires 30d;}

然后过期的标题工作正常。

如果我添加

location ~* \.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf|html|txt|htm)$ {
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
    }
    if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    }
    if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    }
}

然后CORS工作正常。

但是,如果我像这样将它们加在一起,那么只有过期的标头有效,而 cors 停止工作。

location ~*  \.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf|x-html|css|xml|js|woff|woff2|ttf|svg|eot)$ {
expires 30d;}

location ~* \.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|css|rss|atom|js|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf|html|txt|htm)$ {
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        #
        # Custom headers and headers various browsers *should* be OK with but aren't
        #
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        #
        # Tell client that this pre-flight info is valid for 20 days
        #
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        return 204;
    }
    if ($request_method = 'POST') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    }
    if ($request_method = 'GET') {
        add_header 'Access-Control-Allow-Origin' '$http_host';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
        add_header 'Access-Control-Expose-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
    }
}

上述组合有什么问题?我该如何解决?

nginx http-headers cors
  • 2 个回答
  • 1213 Views
Martin Hope
MvG
Asked: 2016-08-30 06:32:12 +0800 CST

允许 CORS 中的所有标头

  • 1

我想将我的 Apache 2.4 配置为以 CORS 友好的方式提供一些静态资源。我已经有以下设置:

Header always set Access-Control-Allow-Origin "*"

但是,对于最近的 Safari,这似乎还不够:

[错误]加载资源失败:请求标头字段… 不允许Access-Control-Allow-Headers。

以这种方式提到的字段包括Accept-Encodingand DNT,但我想在添加它们之后我可能还会看到Cache-Control, Originand Accept-Language,因为这些是Access-Control-Request-HeadersSafari 发送的标头中提到的字段。但是谁能告诉我 Safari 或其他浏览器现在或将来可能会为我自己或其他具有不同配置的用户请求哪些其他标头?由于我不太了解的原因,显然*不是标题的有效设置。Access-Control-Allow-Headers

那么我如何配置服务器只说“在任何地方使用这些资源,我不关心他们的 CORS”?

static-content apache-2.4 apache2 http-headers cors
  • 2 个回答
  • 3642 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    新安装后 postgres 的默认超级用户用户名/密码是什么?

    • 5 个回答
  • Marko Smith

    SFTP 使用什么端口?

    • 6 个回答
  • Marko Smith

    命令行列出 Windows Active Directory 组中的用户?

    • 9 个回答
  • Marko Smith

    什么是 Pem 文件,它与其他 OpenSSL 生成的密钥文件格式有何不同?

    • 3 个回答
  • Marko Smith

    如何确定bash变量是否为空?

    • 15 个回答
  • Martin Hope
    Tom Feiner 如何按大小对 du -h 输出进行排序 2009-02-26 05:42:42 +0800 CST
  • Martin Hope
    Noah Goodrich 什么是 Pem 文件,它与其他 OpenSSL 生成的密钥文件格式有何不同? 2009-05-19 18:24:42 +0800 CST
  • Martin Hope
    Brent 如何确定bash变量是否为空? 2009-05-13 09:54:48 +0800 CST
  • Martin Hope
    cletus 您如何找到在 Windows 中打开文件的进程? 2009-05-01 16:47:16 +0800 CST

热门标签

linux nginx windows networking ubuntu domain-name-system amazon-web-services active-directory apache-2.4 ssh

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve