How does Nginx prohibit cross-domain access to a PHP file?
世界只因有你
世界只因有你 2017-05-16 17:24:55
0
3
892

For example, there is a website a.com, and there is an ajax.php file in the directory. Now it is required that only access to a.com (that is, bound to this domain name) is allowed to receive POST data. Other domain names such as b.com want to POST. When the data is sent to ajax.php, it will directly return 503 or the like. How to write it? I’m not familiar with nginx, it’s best to give specific examples, thank you~

世界只因有你
世界只因有你

reply all(3)
为情所困

I read the document and wrote a few lines of code to solve the problem. I will use this solution for the time being. If you have a better solution, please leave a message.

The code is posted below

        location ~ \.php$ {

        #新增代码 start

        # 假设 ajax.php 文件路径是 /includes/ajax.php 和网站域名是 www.a.com
        # 新增一个变量 $nolocal 值为1,也就是真

        set $nolocal 1;

        #下面开始判断,不是 POST 或者请求路径不是 ajax.php 的路径或者请求来源属于本站域名时,都设为0,也就是假
        #为什么是三个 if 呢?因为 nginx 居然不支持多条件判断,真是醉了~
        if ($request_method != POST) {
                set $nolocal 0;
        }
        if ($request_uri != /includes/ajax.php) {
                set $nolocal 0;
        }
        if ($http_referer ~* "www.a.com") {
            set $nolocal 0;
        }

        #经过上面的筛选,值是真的,也就是其他来源POST数据过来了,直接返回 403 拒绝处理
        #这样,其他来源的请求就浪费不了你的PHP进程了。
        if ($nolocal) {
            return 403;
        }

        #新增代码 end

        root           html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME /var/www/a/$fastcgi_script_name;
        include        fastcgi_params;
    }
左手右手慢动作

Nginx can create multiple sites. That is server{}

in Nginx

Create a default site first:

server {
server_name _;
root /var/nginx/html;
}

Create another site a.com:

server {
server_name a.com www.a.com;
root /data/www/a.com;
}

In this way, only a.com will be able to access files under the path a.com, and other domain names will access files under the default site /var/nginx/html.

阿神
if ($host != 'XXX.com' ) {
    这里写规则。
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!