在 Ubuntu 下配置 PHP 以允许跨域访问,通常需要设置 CORS(跨来源资源共享)头。以下是详细的步骤和示例配置:
如果你使用的是 Apache 服务器,可以通过修改 .htaccess 文件或配置虚拟主机来设置 CORS 头。
.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>
编辑 Apache 的虚拟主机配置文件(通常位于 /etc/apache2/sites-available/ 目录下),添加以下内容:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
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"
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
修改完成后,重启 Apache 服务器:
sudo systemctl restart apache2
如果你使用的是 Nginx 服务器,可以通过修改 Nginx 配置文件来设置 CORS 头。
编辑 Nginx 的配置文件(通常位于 /etc/nginx/sites-available/ 目录下),添加以下内容:
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
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;
}
location ~ /\.ht {
deny all;
}
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;
}
修改完成后,重启 Nginx 服务器:
sudo systemctl restart nginx
如果你不想修改服务器配置文件,也可以在 PHP 脚本中直接设置 CORS 头。在你的 PHP 文件顶部添加以下代码:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
// 你的 PHP 代码
Access-Control-Allow-Origin 设置为特定的域名,而不是 *,以提高安全性。通过以上步骤,你应该能够在 Ubuntu 下成功配置 PHP 以允许跨域访问。