我有一个使用
NGINX
运行的网站,其中有一个 API
和一个 Vue APP
,假设 API
位于 api.example.com
上,而 Vue APP
位于 www.example.com
上,我有一些要求无法使用中间件或其他东西,所以我想知道如何防止 API
被外部调用 example.com
。
我现在正在测试它,我的
Vue APP
在 localhost:8080
上运行,我仍然可以访问它。
我当前的
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.
我找到了一个对我有用的解决方案。也许不是最好的选择,但我认为它有效
location / {
#valid_referers none blocked server_names *.example.com;
#if ($invalid_referer) {
# return 403;
#}
try_files $uri $uri/ /index.php?$query_string;
}