在 Ubuntu 环境下为 PHP 配置跨域访问,核心做法其实很直接,就是在 HTTP 响应头里正确设置 Access-Control-Allow-Origin。具体怎么操作,下面按步骤展开。

1. 安装PHP
如果你还没有安装PHP,可以使用以下命令进行安装:
sudo apt updatesudo apt install php php-cli php-fpm2. 配置PHP-FPM(如果使用)
如果你使用的是PHP-FPM,确保你的Web服务器(如Nginx或Apache)正确配置了PHP-FPM。
Nginx配置示例
编辑Nginx配置文件(通常位于/etc/nginx/sites-a vailable/default),添加以下内容:
server {listen 80;server_name your_domain.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;}}Apache配置示例
编辑Apache配置文件(通常位于/etc/apache2/sites-a vailable/000-default.conf),添加以下内容:
ServerAdmin webmaster@localhostDocumentRoot /var/www/htmlOptions Indexes FollowSymLinksAllowOverride AllRequire all granted ErrorLog ${APACHE_LOG_DIR}/error.logCustomLog ${APACHE_LOG_DIR}/access.log combined 3. 设置跨域访问
你可以通过以下几种方式设置跨域访问:
方法一:在PHP脚本中设置响应头
在你的PHP脚本中添加以下代码:
方法二:使用.htaccess文件(仅适用于Apache)
在你的网站根目录下创建或编辑.htaccess文件,添加以下内容:
Header set Access-Control-Allow-Origin "*"# 或者指定特定的域名# Header set Access-Control-Allow-Origin "http://example.com"方法三:使用Nginx配置
如果你使用的是Nginx,可以在配置文件中添加以下内容:
server {listen 80;server_name your_domain.com;location / {add_header 'Access-Control-Allow-Origin' '*' always;add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;add_header 'Access-Control-Allow-Headers' 'Origin, Content-Type, Accept, Authorization' always;# 其他配置}}4. 重启Web服务器
根据你使用的Web服务器,重启相应的服务以应用更改。
Nginx
sudo systemctl restart nginxApache
sudo systemctl restart apache25. 测试跨域访问
搞定跨域配置后,你的PHP脚本应该能顺畅地响应来自不同域名的请求了。为了保险起见,建议打开浏览器的开发者工具(按F12),仔细检查网络请求的响应头,确认Access-Control-Allow-Origin字段是否如预期般正确设置,这是排除故障的关键一步。
通过以上步骤,你应该能够在Ubuntu上成功配置PHP以实现跨域访问。