在 Ubuntu 上使用 PHP 实现跨域请求(CORS)通常涉及配置服务器以允许来自不同源的 HTTP 请求。以下是几种常见的方法:
mod_headers
模块如果你的服务器运行的是 Apache,可以通过修改 .htaccess
文件或 Apache 配置文件来设置 CORS 头。
步骤:
启用 mod_headers
模块
确保 Apache 的 mod_headers
模块已启用。可以使用以下命令启用:
sudo a2enmod headers
配置 .htaccess
文件
在你的项目根目录下创建或编辑 .htaccess
文件,添加以下内容:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type, Authorization, X-Requested-With"
</IfModule>
说明:
Access-Control-Allow-Origin "*"
允许所有域访问。如果需要限制特定域,可以将 *
替换为具体域名,例如 https://example.com
。Access-Control-Allow-Methods
定义允许的 HTTP 方法。Access-Control-Allow-Headers
定义允许的自定义请求头。重启 Apache 服务器
sudo systemctl restart apache2
如果你不想依赖服务器配置,可以在 PHP 脚本中直接设置 CORS 头。
示例代码:
<?php
// 设置允许的来源
$allowedOrigins = ['https://example.com', 'https://another.com'];
// 获取请求的 Origin
$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
// 检查是否在允许的来源列表中
if (in_array($origin, $allowedOrigins)) {
header('Access-Control-Allow-Origin: ' . $origin);
}
// 设置允许的方法
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
// 设置允许的头
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
// 如果是预检请求,直接返回 200
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
exit;
}
// 继续处理正常的业务逻辑
echo "Hello, CORS!";
?>
说明:
$allowedOrigins
数组中的值为允许访问的域名。如果你的服务器运行的是 Nginx,可以通过修改 Nginx 配置文件来设置 CORS 头。
步骤:
编辑 Nginx 配置文件
打开你的 Nginx 配置文件,通常位于 /etc/nginx/sites-available/your-site
,添加以下内容:
server {
listen 80;
server_name your-domain.com www.your-domain.com;
location / {
# 允许跨域请求
add_header 'Access-Control-Allow-Origin' '*' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Content-Type, Authorization, X-Requested-With' always;
# 处理预检请求
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' 'Content-Type, Authorization, X-Requested-With';
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain charset=UTF-8';
return 200;
}
# 你的其他配置
root /var/www/html/your-project;
index index.php index.html index.htm;
try_files $uri $uri/ /index.php?$query_string;
}
# PHP-FPM 配置
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 根据实际 PHP 版本调整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
测试并重启 Nginx
sudo nginx -t
sudo systemctl restart nginx
Access-Control-Allow-Origin: *
,而是指定具体的域名以提高安全性。OPTIONS
请求,服务器需要正确响应以允许实际的请求。通过以上方法,你可以在 Ubuntu 上使用 PHP 实现跨域请求。根据你的服务器环境和具体需求选择合适的方法进行配置。