在现代 Web 开发中,前端应用经常需要从不同域名的后端服务器获取数据。然而,出于安全考虑,浏览器默认会阻止这种“跨域”请求,这就是所谓的 同源策略(Same-Origin Policy)。为了解决这个问题,我们需要在服务器端配置 跨域资源共享(CORS, Cross-Origin Resource Sharing)。
本文将针对 CentOS 系统,详细讲解如何在常见的 Web 服务器(如 Nginx 和 Apache)中配置 CORS,帮助你轻松解决跨域问题。即使你是 Linux 或服务器配置的新手,也能一步步跟着操作成功!
CORS 是一种 W3C 标准,允许 Web 应用从不同源(协议、域名或端口不同)安全地请求资源。当浏览器检测到跨域请求时,会先发送一个 OPTIONS 预检请求,服务器需正确响应并包含特定的 CORS 头信息,浏览器才会放行实际请求。
CentOS 常搭配 Nginx 或 Apache 作为 Web 服务器。下面分别介绍在这两种服务器上如何启用 CORS。
如果你使用的是 Nginx,请编辑你的站点配置文件(通常位于 /etc/nginx/conf.d/ 或 /etc/nginx/sites-available/)。
server { listen 80; server_name your-domain.com; location /api/ { # 允许所有来源(生产环境建议指定具体域名) add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE'; 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 = 'OPTIONS') { add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } # 你的后端代理或静态文件配置 proxy_pass http://localhost:3000; }} 修改完成后,测试配置并重载 Nginx:
sudo nginx -tsudo systemctl reload nginx 如果你使用的是 Apache,需要启用 mod_headers 模块,并在虚拟主机或 .htaccess 文件中添加 CORS 头。
首先确保模块已启用:
sudo a2enmod headerssudo systemctl restart apache2 然后在你的网站根目录下的 .htaccess 文件中添加以下内容:
# 启用 CORSHeader set Access-Control-Allow-Origin "*"Header set Access-Control-Allow-Methods "GET, POST, OPTIONS, PUT, DELETE"Header set Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range"Header set Access-Control-Expose-Headers "Content-Length,Content-Range"# 处理 OPTIONS 预检请求RewriteEngine OnRewriteCond %{REQUEST_METHOD} OPTIONSRewriteRule ^(.*)$ $1 [R=204,L] 虽然使用 * 可以快速启用 CORS,但在生产环境中强烈建议将 Access-Control-Allow-Origin 设置为具体的前端域名,例如:
add_header 'Access-Control-Allow-Origin' 'https://your-frontend.com'; 这样可以防止其他恶意网站滥用你的 API 接口。
通过本文,你已经学会了在 CentOS 系统下为 Nginx 和 Apache 配置 跨域资源共享(CORS)。无论你使用哪种 Web 服务器,只需添加正确的响应头,就能让前端顺利调用后端接口。
记住关键词:CentOS 跨域资源共享、CORS配置、Nginx跨域设置、Apache跨域解决方案。掌握这些技能,你就能高效解决开发中的跨域难题!
如有疑问,欢迎在评论区留言交流!
本文由主机测评网于2025-12-06发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025123990.html