如何使用 nginx 重定向到多个子域并显示错误页面?
How can I use ngnix to redirect to multiple subdomains and show error pages?
我无法满足 所有 nginx
中的以下条件:
- 当访问 root 时,即
/
,重定向到 /blog
。
- 访问
/app
时,留在/app
。
- 访问其他内容时,例如
/fake/directory
,显示 404 页面。
通常将其中两个的某种组合起作用,但对第三个不起作用。
我尝试过 try_files
按特定顺序使用不同的 location
,return
和 rewrite
的各种组合,但我遗漏了一些细节。
我认为以下方法可行:
location = / {
rewrite / /blog;
}
location ~ /blog.* {
# desired options, php, index, etc.
}
location /app {
# desired options, php, index, etc.
}
location / {
return 404;
}
解释:
- 如果 nginx 找到
=
,它会终止 - 所以 /
没问题
blog
和 apps
位置很简单(我认为)
location /
:是前缀。 nginx
将尝试找到最长的匹配项。 /blog
和 /app
比 /
最长。 /fake/directory
将仅匹配最后一个 location /
,return 404
. 也是如此
更多信息请参阅 nginx location
's documentation
我无法满足 所有 nginx
中的以下条件:
- 当访问 root 时,即
/
,重定向到/blog
。 - 访问
/app
时,留在/app
。 - 访问其他内容时,例如
/fake/directory
,显示 404 页面。
通常将其中两个的某种组合起作用,但对第三个不起作用。
我尝试过 try_files
按特定顺序使用不同的 location
,return
和 rewrite
的各种组合,但我遗漏了一些细节。
我认为以下方法可行:
location = / {
rewrite / /blog;
}
location ~ /blog.* {
# desired options, php, index, etc.
}
location /app {
# desired options, php, index, etc.
}
location / {
return 404;
}
解释:
- 如果 nginx 找到
=
,它会终止 - 所以/
没问题 blog
和apps
位置很简单(我认为)location /
:是前缀。nginx
将尝试找到最长的匹配项。/blog
和/app
比/
最长。/fake/directory
将仅匹配最后一个location /
,return 404
. 也是如此
更多信息请参阅 nginx location
's documentation