当然可以。
这是执行此操作的最小 nginx 配置:
server {
listen 80 default_server;
server_name _;
location / {
rewrite ^.*$ http://squishling.co.uk/errors/incorrect_subdomain.html redirect;
}
}
server {
listen 80;
server_name squishling.co.uk;
location / {
echo some page;
}
location /errors/incorrect_subdomain.html {
echo incorrect subdomain error;
}
}
这是如何运行它:
mkdir conf.d
- 将上面的配置文件放入
conf.d/main.conf
docker run -p80:80 -v ~/work/test/subreq/conf.d:/etc/nginx/conf.d openresty/openresty:alpine
测试
squishling.co.uk 和 foo.squishling.co.uk 在我的 /etc/hosts 中被覆盖,因此它们直接指向我的本地主机
curl -D - http://squishling.co.uk
HTTP/1.1 200 OK
Server: openresty/1.13.6.1
Date: Tue, 06 Feb 2018 18:49:25 GMT
Content-Type: application/octet-stream
Transfer-Encoding: chunked
Connection: keep-alive
some page
现在尝试错误的域
curl -D - http://foo.squishling.co.uk
HTTP/1.1 302 Moved Temporarily
Server: openresty/1.13.6.1
Date: Tue, 06 Feb 2018 18:49:34 GMT
Content-Type: text/html
Content-Length: 167
Connection: keep-alive
Location: http://squishling.co.uk/errors/incorrect_subdomain.html
<html>
<head><title>302 Found</title></head>
<body bgcolor="white">
<center><h1>302 Found</h1></center>
<hr><center>openresty/1.13.6.1</center>
</body>
</html>
或者跟重定向一样:
curl -L -D - http://foo.squishling.co.uk
HTTP/1.1 302 Moved Temporarily
Server: openresty/1.13.6.1
Date: Tue, 06 Feb 2018 18:50:03 GMT
Content-Type: text/html
Content-Length: 167
Connection: keep-alive
Location: http://squishling.co.uk/errors/incorrect_subdomain.html
HTTP/1.1 200 OK
Server: openresty/1.13.6.1
Date: Tue, 06 Feb 2018 18:50:03 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
incorrect subdomain error
因此,主要思想是您定义default 服务器配置,该配置将拦截除具有单独配置的域之外的所有域。其他网络服务器也可以实现同样的功能