menu LittleJake's Blog
color_lens
avatar
Jake Liu
Never Settle
creative commons by-nc-sa
hit
Category
keyboard_arrow_down

© 2024 LittleJake's Blog.

萌ICP备20223020号

Cloudflare获取Typecho评论获取客户端真实IP

前言

CDN开启后无法获取客户端真实ip,只能通过header内的X-Forwarded-For获取。

因此,需要修改typecho配置。

解决方法

  1. 追踪Feedback.phpcomment()方法,得知ip获取方法为$this->request->getIp()
  2. 步入获取到这一段代码:
    switch (true) {
                 case defined('__TYPECHO_IP_SOURCE__') && NULL !== $this->getServer(__TYPECHO_IP_SOURCE__):
                     list($this->_ip) = array_map('trim', explode(',', $this->getServer(__TYPECHO_IP_SOURCE__)));
                     break;
                 case NULL !== $this->getServer('REMOTE_ADDR'):
                     $this->_ip = $this->getServer('REMOTE_ADDR');
                     break;
                 case NULL !== $this->getServer('HTTP_CLIENT_IP'):
                     $this->_ip = $this->getServer('HTTP_CLIENT_IP');
                     break;
                 default:
                     break;
             }
  3. 得知只要在config.inc.php设置常量__TYPECHO_IP_SOURCE__即可获取:
    //开启cloudflare真实IP
    define('__TYPECHO_IP_SOURCE__', 'HTTP_X_FORWARDED_FOR');

后记

见到网上天花乱坠的解决方法,比如通过$_SERVER['HTTP_X_FORWARDED_FOR']覆盖了$_SERVER['REMOTE_ADDR']的方式。其实道理相同,只是这个方式更为简便,设置常量即可。

HTTP_X_FORWARDED_FOR

Buy me a beer
Jake Liu
Never Settle

Title: Cloudflare获取Typecho评论获取客户端真实IP

Author: Jake Liu

Origin:

Creative Commons License

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0) For any re-post you must give appropriate credit.

文章遵循CC许可 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 转载请注明出处

Tag:typecho, cloudflare, ip

评论区

4 comments.

  1. Jake Liu
    2022-02-26 12:00
    WindowsWindows Google ChromeGoogle Chrome

    123

  2. Jake Liu
    2021-12-15 19:06
    WindowsWindows Google ChromeGoogle Chrome

    测试

    1. Jake Liu
      2022-02-26 11:54
      Windows Google Chrome

      1

    2. Jake Liu
      2022-02-26 11:54
      Windows Google Chrome

      1

Add a new comment.

Theme