Welcome! Log In Create A New Profile


How to block API calls outside its own domain ( NGINX )

Posted by gbast0s 
How to block API calls outside its own domain ( NGINX )
November 24, 2023 07:43AM
I have a website running with NGINX where I have an API and a Vue APP, let's say API it's on api.example.com and the Vue APP it's on www.example.com and I have some requests that I can't use a middleware or something, so I would like to know how can I prevent the API from being called outside example.com.

I'm testing it right now with my Vue APP running on localhost:8080, and I still can access it.

My current NGINX config for the API is

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

I tryed to use

ㅤadd_header Access-Control-Allow-Origin "https://www.example.com";

But I got this

ㅤ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.
Sorry, only registered users may post in this forum.

Click here to login

Online Users

Guests: 284
Record Number of Users: 8 on April 13, 2023
Record Number of Guests: 421 on December 02, 2018
Powered by nginx      Powered by FreeBSD      PHP Powered      Powered by MariaDB      ipv6 ready