Nginx配置同一个域名同时支持http与https两种方式访问

Nginx配置同一个域名http与https两种方式都可访问,证书是阿里云上免费申请的

server
{
listen 80;
listen 443 ssl;
ssl on;
server_name 域名;
index index.html index.htm index.php default.html default.htm default.php;
ssl_certificate /usr/local/nginx/cert/21402058063066221.pem; //下载申请后阿里ssh提供的pem
ssl_certificate_key /usr/local/nginx/cert/21402058063066221.key;//下载申请后阿里ssh提供的key
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
root /home/wwwroot/网站目录;
include laravel.conf; //好吧,这里是laravel配置,不一定合适您哈,请或略
#error_page 404 /404.html;
include enable-php.conf;
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 12h;
}
access_log /home/wwwlogs/airclass.mime.org.cn.log;
}

关键在于上面的listen 80;

listen 443 ssl; 开启80端口

当然,这样玩就没有啥意义了,既然是https,就完全没必要http传输数据啦.我们必须把所有http请求转发到https,

把http重定向到https使用了nginx的重定向命令。那么应该如何写重定向?之前老版本的nginx可能使用了以下类似的格式。

也就是再添加一个虚拟机server,80端口一个

server {
listen 80;
server_name www.domain.com;
rewrite ^/(.*) https://$server_name$1 permanent; #跳转到Https
}

重写依旧不同版本可能如下

rewrite ^/(.*)$ https://domain.com/$1 permanent;

或者

rewrite ^ https://domain.com$request_uri? permanent;

现在nginx新版本已经换了种写法,上面这些已经不再推荐。现在网上可能还有很多文章写的是第一种。

下面是nginx http页面重定向到https页面最新支持的写法:

server {
listen 80;
server_name domain.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
server_name domain.com;
}

但是我的nginx/1.10.0好像跑不起来,也许不支持这种写法吧...

下面是基于http转https的完整配置:

server
{
#listen 80;
listen 443;
ssl on;
server_name domain.com; //你的域名
index index.html index.htm index.php default.html default.htm default.php;
ssl_certificate /usr/local/nginx/cert/user.medsci-tech.com/214020580630662.pem;
ssl_certificate_key /usr/local/nginx/cert/user.medsci-tech.com/214020580630662.key;
ssl_session_timeout 5m;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
root /home/wwwroot/web/public;//项目根目录
include laravel.conf;
#error_page 404 /404.html;
include enable-php.conf;
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 12h;
}
}
server {
listen 80;
server_name domain.com;
rewrite ^/(.*) https://$server_name$request_uri? permanent;
}

原文:https://www.cnblogs.com/phpper/p/6441475.html

您可能还会对下面的文章感兴趣: