在现代Web开发中,跨域资源共享(Cross-Origin Resource Sharing,简称CORS)是一个常见但又容易让人困惑的问题。当你在本地开发环境使用Vue、React等前端框架调用部署在Ubuntu服务器上的API时,浏览器往往会因“同源策略”而阻止请求。本文将手把手教你如何在Ubuntu系统上为常见的Web服务器(如Apache和Nginx)配置CORS,彻底解决跨域问题。

当你的网页(例如运行在 http://localhost:3000)尝试向另一个域名或端口(例如 http://your-ubuntu-server.com:8080)发起请求时,浏览器会认为这是“跨域”行为。出于安全考虑,浏览器默认会阻止这类请求,除非服务器明确允许。
要在Ubuntu服务器上启用CORS,你需要根据你使用的Web服务器(如Apache或Nginx)进行相应配置。下面分别介绍两种主流服务器的配置方法。
如果你的Ubuntu服务器使用的是Apache,请按以下步骤操作:
mod_headers 模块(用于设置HTTP响应头):sudo a2enmod headerssudo systemctl restart apache2/etc/apache2/sites-available/ 目录下),例如 000-default.conf,在 <VirtualHost> 块中添加以下内容:<VirtualHost *:80> ServerName your-domain.com DocumentRoot /var/www/html <Directory /var/www/html> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> # 启用CORS Header always set Access-Control-Allow-Origin "*" Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS" Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, X-Token"</VirtualHost>sudo systemctl restart apache2⚠️ 注意:Access-Control-Allow-Origin "*" 表示允许所有域名访问。在生产环境中,建议替换为具体的前端域名,例如 "https://your-frontend.com",以提高安全性。
如果你使用的是Nginx,配置方式略有不同:
/etc/nginx/sites-available/),例如 default。server 块中添加以下CORS相关头部:server { listen 80; server_name your-domain.com; root /var/www/html; index index.html index.htm; # CORS 配置 location / { if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,X-Token'; add_header 'Access-Control-Max-Age' 1728000; add_header 'Content-Type' 'text/plain; charset=utf-8'; add_header 'Content-Length' 0; return 204; } add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,X-Token'; try_files $uri $uri/ =404; }}sudo nginx -tsudo systemctl reload nginx你可以使用浏览器开发者工具(F12 → Network 标签)查看API请求的响应头,确认是否包含以下字段:
Access-Control-Allow-OriginAccess-Control-Allow-MethodsAccess-Control-Allow-Headers如果看到这些字段,说明你的Ubuntu跨域资源共享配置已成功!
通过本文,你已经学会了如何在Ubuntu系统上为Apache和Nginx服务器配置CORS。无论你是前端开发者还是运维人员,掌握这些基础配置都能显著提升开发效率。记住,在生产环境中务必限制 Access-Control-Allow-Origin 的值,避免安全风险。
希望这篇关于Ubuntu跨域资源共享配置的教程对你有帮助!如果你还有其他问题,欢迎在评论区留言交流。
本文由主机测评网于2025-12-05发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025123449.html