我正在尝试重定向:
pt.example.com and example.com
到
https://pt.example.com
pt.example.com
将重定向至https://pt.example.com
。没关系。example.com
将重定向至https://example.com
(不https://pt.example.com
符合预期)
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name pt.example.com;
return 301 https://pt.example.com$request_uri;
}
我该如何改正?
答案1
由于您的域名已经有默认服务器,我会假定这是托管在该 IP 地址的唯一域名。
将其中一个server
块设为默认服务器,并将另一个server
块设置为 true server_name
。默认服务器同时侦听端口 80 和 443,不需要语句server_name
。
如果两个域共享相同的证书,则可以将ssl_certificate
指令移动到两个server
块上方,如我的示例所示。
ssl_certificate ...;
ssl_certificate_key ...;
server {
listen 80 default_server;
listen [::]:80 default_server;
listen 443 ssl default_server;
listen [::]:443 ssl default_server;
return 301 https://pt.example.com$request_uri;
}
server {
listen 443 ssl;
listen [::]:443 ssl;
server_name pt.example.com;
#
# this is your main server block for https://pt.example.com
#
}
看这个文件了解更多信息。
答案2
为了使 HSTS 正常工作,您需要在同一主机名上从 http 重定向到 https,然后在 https 上从第一个主机名重定向到第二个主机名。
这也意味着两个主机名都必须具有 TLS 证书。理想情况下,它们应该是同一证书上的备用名称,以简化维护。
以下是从我的一个生产站点中提取的实时工作示例:
server {
server_name www.yes-www.org yes-www.org;
include includes/listen-80;
include includes/cloudflare;
include includes/letsencrypt;
access_log off;
return 301 https://$host$request_uri;
}
上面,我们只是在同一个主机名上从 http 重定向到 https,无论它是什么。
server {
server_name yes-www.org;
ssl_certificate /etc/letsencrypt/live/www.yes-www.org/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/www.yes-www.org/privkey.pem;
include includes/listen-443;
include includes/cloudflare;
include includes/ssl;
include includes/ssl_stapling;
include includes/hsts;
include includes/letsencrypt;
return 301 https://www.yes-www.org$request_uri;
}
这里我们通过 https 从一个主机名重定向到另一个主机名。目标主机名在return
指令中。
server
如果您有其他主机名需要从一个主机名重定向到目标主机名,只要它们共享相同的 TLS 证书,它们都可以从同一个块中提供服务。否则,请复制该server
块。
server {
server_name www.yes-www.org;
root /srv/www/yes-www.org;
access_log /var/log/nginx/yes-www.org-access.log nginx;
access_log /var/log/nginx/cache.log cache;
error_log /var/log/nginx/yes-www.org-error.log;
ssl_certificate /etc/letsencrypt/live/www.yes-www.org/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/www.yes-www.org/privkey.pem;
include includes/listen-443;
include includes/cloudflare;
include includes/letsencrypt;
include includes/ssl;
include includes/ssl_stapling;
include includes/hsts;
# more directives to serve the web app itself
# which you should replace with your own directives
# to serve your own web app
}
当然,这只是为网站服务。