![使用 NGINX 重定向特定子域名以在使用 SSL 时指向其他网站](https://linux22.com/image/785123/%E4%BD%BF%E7%94%A8%20NGINX%20%E9%87%8D%E5%AE%9A%E5%90%91%E7%89%B9%E5%AE%9A%E5%AD%90%E5%9F%9F%E5%90%8D%E4%BB%A5%E5%9C%A8%E4%BD%BF%E7%94%A8%20SSL%20%E6%97%B6%E6%8C%87%E5%90%91%E5%85%B6%E4%BB%96%E7%BD%91%E7%AB%99.png)
我有以下 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 子域