Nginx 实现域名验证的三种配置方案
各大公众平台在配置接口域名时,需要验证开发者对该域名的控制权。具体做法是生成一段随机的文本或字符串,要求将其放置在域名根目录下,确保能通过域名直接访问该文件,从而完成验证流程。
以验证域名 abc.com 为例,系统要求在根路由下可访问文件 6CysNYj8Hb.txt,其响应体内容应为字符串 01df2ddab4774ba2676a5563ccb79ffa。
$ curl https://abc.com/6CysNYj8Hb.txt
01df2ddab4774ba2676a5563ccb79ffa
方案一
如果 Nginx 配置中已经设置了 root 指令的 server 块,只需将随机生成的文档直接放入该 root 指定的目录下即可。此方法无需重启 Nginx 服务即可生效。
方案二
通过匹配特定的路由路径,并指定随机文档所在的目录。这种方式需要在修改配置后重启 Nginx 服务才能生效。
location ~* 6CysNYj8Hb\.txt {
root /data/ftp;
}
方案三(推荐)
同样通过匹配路由,但直接在配置中返回需要验证的随机字符串,而不依赖外部文件。此方法也需要重启 Nginx 服务。
location = /6CysNYj8Hb.txt {
default_type text/html;
return 200 '01df2ddab4774ba2676a5563ccb79ffa';
}
参考
Nginx 的 Location 从零开始配置
nginx 配置返回文本或 json
补充:Nginx域名重定向
1、更改配置文件test.com.conf
[root@jimmylinux-001 vhost]# vim test.com.conf
server
{
listen 80;
server_name test.com test2.com test3.com;
index index.html index.htm index.php;
root /data/wwwroot/test.com;
if ($host != 'test.com' ) {
rewrite ^/(.*)$ http://test.com/$1 permanent;
}
}
2、curl测试
[root@jimmylinux-001 vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@jimmylinux-001 vhost]# /usr/local/nginx/sbin/nginx -s reload
[root@jimmylinux-001 vhost]# curl -x127.0.0.1:80 test2.com/index.html -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Thu, 07 Jun 2026 16:47:36 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://test.com/index.html
[root@jimmylinux-001 vhost]# curl -x127.0.0.1:80 test2.com/admin/index.html -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Thu, 07 Jun 2026 16:48:08 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://test.com/admin/index.html
[root@jimmylinux-001 vhost]# curl -x127.0.0.1:80 test3.com/admin/index.html/adjlfj -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Thu, 07 Jun 2026 16:48:35 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://test.com/admin/index.html/adjlfj
[root@jimmylinux-001 vhost]# curl -x127.0.0.1:80 test4.com/admin/index.html/adjlfj -I
HTTP/1.1 404 Not Found
Server: nginx/1.12.1
Date: Thu, 07 Jun 2026 16:48:43 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。