需求
1、网站的一个子目录用https打开,其他子目录、页面和首页仍然使用http方式访问。
2、用https访问其他子目录、页面和首页时跳转到http访问,用http访问指定子目录时跳转到https访问。
步骤
获得ssl证书
这里博主选择了沃通的免费ssl证书,申请还是比较简单的,而且也比startssl方便。申请地址:https://buy.wosign.com/FreeSSL.html 。申请成功后他家会给你一个压缩包,选择nginx那个,配置nginx ssl的时候要用到。
nginx开启ssl
打开nginx配置文件,在原配置后面添加如下内容。
server{
listen 443 ;
server_name www.nbhao.org;
index index.html index.htm index.php;
root /home/www/nbhao;
ssl on ;
ssl_certificate /etc/nginx/ssl/www.nbhao.org.crt ; #换成自己证书的地址
ssl_certificate_key /etc/nginx/ssl/www.nbhao.org.key ;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; #下面内容可以不加,主要是想提高ssl的性能。
ssl_ciphers ECDHE-RSA-AES256-SHA384:AES256-SHA256:RC4:HIGH:!MD5:!aNULL:!eNULL:!NULL:!DH:!EDH:!AESGCM;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
location ~ .*/webproxy/.*\.(php|php5)?$
{
try_files $uri =404;
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fcgi.conf;
fastcgi_param HTTPS on;
}
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 12h;
}
access_log /var/log/www/www.nbhao.org.log www.nbhao.org;
}
添加保存后,重启nginx。这时可以通过https://www.nbhao.org/webproxy访问这个页面。
nginx子目录、http和https之间的重定向
这里因为博主的nginx是老版本,所以重定向命令仍然使用老方法。如果您用的是比较新的nginx,需要把nginx的重定向命令换一下,具体详见:http://blog.nbqykj.cn/?p=1829.html 。
打开网站配置文件,找到类似下面的一段代码。
server
{
listen 80;
server_name www.nbhao.org;
index index.html index.htm index.php default.html default.htm default.php;
......
#access_log off;
access_log /var/log/www/www.nbhao.org.log www.nbhao.org;
}
在这之间添加如下内容:
if ($request_uri ~ ^/webproxy(/)?.*){
rewrite ^(.*) https://$server_name$1 permanent;
}
意思是如果以http方式访问http://www.nbhao.org/webproxy这个页面,那么就跳转到https://www.nbhao.org/webproxy 。
再找到刚刚配置ssl添加的那段,在server {}中间添加如下内容:
location / {
if ($request_uri !~ ^/webproxy(/)?.*){
rewrite ^(.*) http://$server_name$1 permanent;
}
}
意思是如果以https方式访问的不是https://www.nbhao.org/webproxy这个页面,那么就跳转到http访问。
配置总结
在配置ssl的时候碰到一个问题,如果之前在这台服务器上配置过ssl,那么需要把这个配置文件删除掉,不然访问的时候浏览器会提示ssl证书和访问地址不对应的警告。
另外如果https方式运行$_SERVER[‘HTTPS’]这个php命令的时候提示off或者空,那么需要在nginx中添加fastcgi_param HTTPS on; 。
