我有一个使用 NGINX 运行的网站,其中有一个 API 和一个 Vue APP,假设 API 位于 api.example.com 上,Vue APP 位于www.example.com并且我有一些不能使用中间件或其他东西的请求,所以我想知道如何防止在 example.com 之外调用 API。
我现在正在使用在 localhost:8080 上运行的 Vue APP 进行测试,我仍然可以访问它。
我当前的 NGINX API 配置是
server {
server_name api.example.com;
root /var/www/api/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
index index.php;
charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
我尝试使用
add_header Access-Control-Allow-Origin "https://www.example.com";
但我得到了这个
Access to XMLHttpRequest at 'https://api.example.com/api/what' from origin 'https://www.example.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values '*, https://www.example.com', but only one is allowed.