nginx/apache 配置静态资源允许跨域访问

有时为了优化网站访问速度,会给一些静态资源配置cdn加速,但是有时候会出现跨域访问的问题,在nginx和apache服务中可进行如下配置

1. apache

找到apache配置文件httpd.conf

找到这行

#LoadModule headers_module modules/mod_headers.so

把#注释符去掉

LoadModule headers_module modules/mod_headers.so

目的是开启apache头信息自定义模块

在独立主机配置文件中新增header

Header set Access-Control-Allow-Origin *

例如:

<VirtualHost *:88>
  ServerAdmin admin@example.com
  DocumentRoot "****************"
  ServerName www.jianzhi12.com
  Header set Access-Control-Allow-Origin *

  ErrorLog "***********"
  CustomLog "****************************" common
<Directory "**************">
  SetOutputFilter DEFLATE
  Options FollowSymLinks ExecCGI
  Require all granted
  AllowOverride All
  Order allow,deny
  Allow from all
  DirectoryIndex index.html index.php
</Directory>
</VirtualHost>
ApacheCopy

意思是对这个域名的资源进行访问时,添加一个头信息

重启apache

service httpd restart

2. nginx

同理 找到相应域名配置文件

在server模块中添加配置:

add_header ‘Access-Control-Allow-Origin’ ‘*’;1

例:

server {
        listen       80;
        add_header 'Access-Control-Allow-Origin' '*';
        location /Roboto/ {
            root   /home/images;
            autoindex on;
        }
    }

nginx重载

./nginx -s reload
标签:NginxApache 发布于:2019-10-03 02:06:08