Nginx环境下http和https可同时访问方法

以下方法可以支持http和https同时访问

server {
listen 80;
listen 443 ssl spdy_detect spdy;
add_header Strict-Transport-Security “max-age=31536000; includeSubDomains”;
ssl_certificate /usr/local/nginx/conf/ca/lijun.me.crt;
ssl_certificate_key /usr/local/nginx/conf/ca/lijun.me.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5:!EXPORT56:!EXP;
ssl_prefer_server_ciphers on;
include /usr/local/nginx/conf/sql.acl;
server_name www.lijun.me lijun.me;
if ($host != “www.lijun.me”)
{
rewrite ^/(.*)$ https://www.lijun.me/$1 permanent;
}

如果按照以下配置访问http回报400错误

server {
listen 80;
listen 443;
ssl on;
  ssl_certificate /usr/local/nginx/conf/ca/lijun.me.crt;
ssl_certificate_key /usr/local/nginx/conf/ca/lijun.me.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5:!EXPORT56:!EXP;
ssl_prefer_server_ciphers on;
}
访问http回报错400

400 Bad Request

The plain HTTP requset was sent to HTTPS port

只需要把ssl on;去掉,ssl写在443端口的后面即可支持http和https的连接都可以访问.

如果需要强制跳转去https,对端口或者host进行判断,然后rewrite

if ($server_port != 443) {

rewrite (.*) https://$host$1 permanent;

}

or

if ( $host != www.lijun.me)

rewrite (.*) https://$hosts$1 permanent;

}

此条目发表在Nginx分类目录,贴了标签。将固定链接加入收藏夹。

发表评论

电子邮件地址不会被公开。 必填项已用*标注