随着国内网站越来越多的从http转向更安全的https方式,需要开启https,但同时又要保证原有的http通道正常访问,在很多情况下会使用Nginx来做反向代理,并做http到https的跳转。
Nginx配置SSL并把Http跳转到Https,需要修改Nginx.conf配置文件:
#原80端口做301转跳
server {
listen 80;
server_name w3cschool.cn www.w3cschool.cn;
return 301 https://www.zhimiyun.com$request_uri; #跳转到Https
}
#配置ssl证书和开启ssl功能
server {
listen 443;
server_name www.w3cschool.cn;
root wwwroot;
index index.html index.htm;
ssl on;
ssl_certificate /usr/ssl/ca.pem; #证书地址
ssl_certificate_key /usr/ssl/ca.key;
ssl_session_timeout 5m;
ssl_protocols SSLv2 SSLv3 TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
ssl_prefer_server_ciphers on;
error_page 497 "https://$host$uri?$args"; #这是跳转Http请求到Https
location / {
...
}
}
也就是再添加一个虚拟机server,80端口一个,443端口一个。
但是有些程序只会给你往端口上转发,不会自动修正http为https,这样的程序还不少,例如phpmyadmin:
遇到这样的程序我们需要修改Nginx.conf配置文件,在443的server的fastcgi字段中添加一个语句:
fastcgi_param HTTPS on; #attention!#
例如:
location ~ .*\.(php|php5)?$
{
try_files $uri =404;
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
fastcgi_param HTTPS on; #attention!#
include fcgi.conf;
}
注释:
把http重定向到https使用了nginx的重定向命令。那么应该如何写重定向?之前老版本的nginx可能使用了以下类似的格式。
rewrite ^/(.*)$ http://domain.com/$1 permanent;
或者
rewrite ^ http://domain.com$request_uri? permanent;
现在nginx新版本已经换了种写法,上面这些已经不再推荐。现在网上可能还有很多文章写的是第一种。新的写法比较推荐方式是:
return 301 http://domain.com$request_uri;
原文链接:Nginx配置SSL及Http跳转到Https,转载请注明来源!