我正在努力如何在我的网站(nginx)上强制使用SSL . 我想从“http://www.example.com " and " http://example.com " to " https://example.com”(没有任何www)强制重定向 .
我当前写的代码可以捕获“http://www.example.com " but does not catch " http://example.com ", it seems to infinite loop a redirection. I'm pretty sure it has something to do with the " server_name ". I tried swapping it up a down inside the " server ”括号和东西,但它仍然没有按照我希望的方式运行 .
这是我的nginx conf
server {
server_name www.example.com;
return 301 https://example.com$request_uri;
}
server {
server_name example.com;
root /var/www/example.com;
index index.html index.php index.htm;
location / {
include /etc/nginx/conf/fastcgi_params;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root/$fastcgi_script_name;
}
location ~ /\.ht {
deny all;
}
}
server {
#listen 443 spdy default deferred;
ssl on;
ssl_certificate_key /etc/myssl/www.example.com.key;
ssl_certificate /etc/myssl/www.example.com.chained.crt;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers 'ECDHE-RSA-AES128-[...]';
ssl_prefer_server_ciphers on;
ssl_dhparam /usr/share/myssl/dhparams/dh2048-group14.pem;
ssl_session_timeout 5m;
ssl_session_cache shared:SSL:5m;
add_header Strict-Transport-Security max-age=15768000;
}
1 回答
您需要配置每个
server
块以专门侦听某个端口,例如:这表示在HTTP(端口80)上侦听http://www.example.com和http://example.com的请求,并将它们重定向到https://example.com . 第二个块侦听https://www.example.com并重定向到https://example.com . 然后,最后一个块侦听对https://example.com的SSL / SPDY请求 .
将剩余的仅HTTPS配置添加到第二个块,该块看起来基本上是合并第二个和第三个块 .
现在在示例中演示了以下内容:如果您希望服务器响应或重定向访问https://www.example.com的用户,则需要添加另一个
server
块,因此您可能需要第二个有效的SSL证书(一个用于www.example.com,一个用于example.com) . 或者,通配符证书或具有备用DNS名称的证书可以适用于这两种情况 .还要确保配置目录中不存在其他冲突的配置文件(例如
/etc/nginx/conf.d
或/etc/nginx/sites-enabled
;具体取决于您的平台) .Edited: 根据给出的其他信息进行了扩展 .