当我使用 SSL 设置网站时,我几乎总是有这个样板 nginx 配置(注释中的说明):
# Redirect both (http/https) non www. to www.
server {
listen 80;
listen 443 ssl;
ssl_certificate /etc/ssl/certs/www.example.com.pem;
ssl_certificate_key /etc/ssl/private/www.example.com.key;
server_name example.com;
return 301 $scheme://www.example.com$request_uri;
}
# Redirect www. http traffic to www. https
server {
listen 80;
server_name www.example.com;
return 301 https://$host$request_uri;
}
# Serve www. website over https
server {
listen 443 ssl;
ssl_certificate /etc/ssl/certs/www.example.com.pem;
ssl_certificate_key /etc/ssl/private/www.example.com.key;
server_name www.example.com;
root /home/example/apps/site;
server_tokens off;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
# ...
}
有人有建议让这个变得更简单并消除一些重复吗?
答案1
如果您有 的通配符证书*.example.com
,则可以按照以下形式书写:
server {
listen 80 default_server;
listen 443 ssl default_server;
ssl_certificate /etc/ssl/certs/www.example.com.pem;
ssl_certificate_key /etc/ssl/private/www.example.com.key;
return 301 https://www.example.com$request_uri;
}
server {
listen 443;
server_name www.example.com;
root /home/example/apps/site;
index index.php index.html index.htm;
server_tokens off;
location / {
try_files $uri $uri/ =404;
}
[ ... ]
}
SSL 握手总是会在第一个块中发生,从而提供通配符域证书。
由于是 SSL,因此选举server_name
是在握手之后完成的,并允许这种配置形式,其中正确的服务器块不一定是发生握手的服务器块。
该default_server
指令将强制将未知/空/不存在的主机标头重定向到 HTTPS 域。