我有以下 NGINX 配置:
# HTTP Redirect
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
# HTTPS Server
server {
# Port to listen on, can also be set in IP:PORT format
listen 443 ssl;
ssl_certificate bitnami/certs/server.crt;
ssl_certificate_key bitnami/certs/server.key;
include "/opt/bitnami/nginx/conf/bitnami/*.conf";
location /status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
error_page 404 403 500 503 /404.html;
location = /404.html {
root /opt/bitnami/nginx/html;
internal;
}
}
它的工作效果非常好,可以访问我的网站并根据需要将任何 HTTP 重定向到 HTTPS。我现在想做的是给定一个子域,例如media.website.com
,我想将其重定向到不同的域/位置,但保持所有内容不变。(即,如果我访问website.com
它,它仍会将我带到我的主站点。)我还希望此重定向适用于 HTTP 和 HTTPS。
我怎样才能做到这一点?
答案1
您应该添加新的server
块,以便处理特定的子域,这里是包含 2 个新块的配置文件
# HTTP Redirect
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 301 https://$host$request_uri;
}
# HTTPS Server
server {
listen 443 ssl;
ssl_certificate bitnami/certs/server.crt;
ssl_certificate_key bitnami/certs/server.key;
server_name website.com www.website.com;
include "/opt/bitnami/nginx/conf/bitnami/*.conf";
location /status {
stub_status on;
access_log off;
allow 127.0.0.1;
deny all;
}
error_page 404 403 500 503 /404.html;
location = /404.html {
root /opt/bitnami/nginx/html;
internal;
}
}
# Redirect media.website.com (HTTP)
server {
listen 80;
server_name media.website.com;
return 301 https://media.website.com$request_uri;
}
# Redirect media.website.com (HTTPS)
server {
listen 443 ssl;
server_name media.website.com;
ssl_certificate bitnami/certs/server.crt;
ssl_certificate_key bitnami/certs/server.key;
return 301 https://newdomain.com$request_uri;
}
我们还将其添加server_name directive
到现有的 HTTPS 服务器块中,以明确指定主域及其 www 子域