Nginx 直接返回请求IP(获取公网IP)

Scroll Down

网上已有免费的获取公网IP的服务,一般不会出现不能访问的情况,但因之前我做DDNS的时候,出现过第三方服务不能访问的情况,在此记录一下自己搭建一个服务,实用Nginx即可获取公网IP,配置以下

server {
    server_name whatismyip.wintewu.com;
    location / {
        add_header Content-Type "text/plain;charset=utf-8";
        return 200 "$remote_addr";
    }

    listen 443 ssl;
    ssl_certificate /etc/letsencrypt/live/wintewu.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/wintewu.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
}
server {
    if ($host = whatismyip.wintewu.com) {
        return 301 https://$host$request_uri;
    }
    listen 80;
    server_name whatismyip.wintewu.com;
    return 404;
}

非常简单,核心就是下面代码,当然你也可以自己拼接成JSON格式,等等

location / {
    add_header Content-Type "text/plain;charset=utf-8";
    return 200 "$remote_addr";
}