Search code examples
phpsecuritynginxxsscsrf

Only allow my server to execute a script in PHP


What is the best way to prevent executing a PHP script from other hosts? Basically, I only want my server web1.mydomain.com to execute the PHP script. Right now, if I create a html file with an iframe or img tag that points to my script on a different domain and call it, it works and executes. I want to prevent this.

Is it possible to do this at the web server level instead of PHP application code? I am using nginx. That would be the best solution.


Solution

  • This would seem to be a textbook case of what the valid_referers nginx directive is for.

    Add something like the following to the location-block for your script:

    valid_referers web1.mydomain.com;
    

    or if you want to be bit less strict, and more tolerant of stripped/obfuscated referers:

    valid_referers none blocked web1.mydomain.com;
    

    see http://nginx.org/en/docs/http/ngx_http_referer_module.html#valid_referers for more info