我需要创建一个 apache 服务器来托管我的文件并通过 ajax 获取它们。因此,我使用 docker 来部署我的服务器。
我的docker镜像是httpd:2.4。
我使用以下命令部署服务器:
docker run -p 80:80 -dit --name file-server \
-v /sources/docker/apache-server/www/:/usr/local/apache2/htdocs/ httpd:2.4
但是当我想发出ajax请求时,结果是这样的:
XMLHttpRequest 无法加载 http://server/kml/example.kml。不 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许访问原点“null”。
所以,我想执行以下步骤如何为 Apache httpd 服务器启用 CORS? (分步过程)。但我不知道如何在组件的 httpd.conf 中添加该命令。而且我没有 httpd.conf 模板来替换它:
v /sources/docker/apache-server/my-httpd.conf:/usr/local/apache2/conf/httpd.conf
请帮我解答这个问题。
您可以使用命令
docker exec -it nameContainer sh
在 shell 终端中输入。在终端中写入: su 使用这些命令现在您是 Docker 中的 root 用户。
现在在终端中,您必须编写
a2enmod headers
并重新启动 docker
最后一个命令是激活 mod_header ,现在您已经在项目根文件中创建了一个 .htaccess 并在其中写入:
Header add Access-Control-Allow-Origin "*"
对我来说工作得很好,不需要在我的机器上安装 apache
这个问题肯定已经在其他地方得到解决,并且有许多不同的解决方案,但是这是“cors apache docker”的第一个搜索结果,所以这是我的 2 美分:
最好的解决方案(因为它是可审核和可重复)是使用
docker build
命令和 Dockerfile
使用 apache docker 映像作为您自己的映像的基础。我不会详细讨论这个问题,因为这不是这里的直接问题,但基本部分是相同的。
使用 CORS 标头位创建一个“额外”的 apache 配置文件:
me@mymachine:~$ docker exec file-server bash -c 'printf "<Directory \"/var/www/html\">\n Header set Access-Control-Allow-Origin \"*\"\n</Directory>\n" >> /usr/local/apache2/conf/extra/cors.conf'
me@mymachine:~$ docker exec file-server bash -c 'tail /usr/local/apache2/conf/extra/cors.conf'
<Directory "/var/www/html">
Header set Access-Control-Allow-Origin "*"
</Directory>
重新启动 apache 以使用这个新配置:
me@mymachine:~$ docker exec file-server bash -c 'apachectl -k restart'
注意:如果您没有在任何地方配置
ServerName
,那么您可能会看到此与 CORS 配置无关的警告:
AH00558: httpd: Could not reliably determine the server's fully qualified domain name, using 172.17.0.3. Set the 'ServerName' directive globally to suppress this message