随着微信小程序和appstore对ssl安全的需求,越来越多的网站和app需要支持SSL功能,需要开启https的方式来打开网站或传输数据。
ssl证书网上可以找到收费和免费的申请,nginx配置如下:
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;
转载本站内容时,请务必注明来自W3xue,违者必究。