在Ubuntu系统中,使用PHP-FPM时,要实现跨域访问控制,可以通过以下几种方法:
安装Nginx(如果尚未安装):
sudo apt update
sudo apt install nginx
配置Nginx:
编辑Nginx配置文件,通常位于/etc/nginx/sites-available/your-site。
server {
    listen 80;
    server_name your-domain.com;
    location / {
        root /var/www/html;
        index index.php index.html index.htm;
        # 允许跨域访问
        add_header 'Access-Control-Allow-Origin' '*' always;
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
        add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept, Authorization' always;
        # 处理预检请求
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept, Authorization';
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            add_header 'Content-Length' 0;
            return 204;
        }
        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;
    }
}
启用配置: 创建一个符号链接以启用站点配置:
sudo ln -s /etc/nginx/sites-available/your-site /etc/nginx/sites-enabled/
测试配置并重启Nginx:
sudo nginx -t
sudo systemctl restart nginx
如果你不想通过Nginx配置CORS,也可以在PHP代码中设置CORS头。
在你的PHP文件中添加以下代码:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
// 你的PHP代码
你可以使用一些Composer包来简化CORS头的设置,例如fruitcake/laravel-cors(适用于Laravel,但也可以在其他PHP项目中使用)。
安装包:
composer require fruitcake/laravel-cors
配置包:
在config/cors.php中配置CORS选项。
*允许所有域访问可能会带来安全风险。建议根据实际需求限制允许的域。通过以上方法,你可以在Ubuntu系统中使用PHP-FPM实现跨域访问控制。