[转帖]nginx 80端口重定向 转发到443端口

时间:2021-04-26 07:04:25

nginx 80端口重定向到443端口

2017年05月16日 13:53:58 幸福丶如此 阅读数 33387
 
版权声明:本文为博主原创文章,遵循CC 4.0 by-sa版权协议,转载请附上原文出处链接和本声明。

nginx 80端口重定向到443端口,也就是http访问自动跳转到https 
配置如下: 
一、按照如下格式修改nginx.conf 配置文件,80端口会自动转给443端口,这样就强制使用SSL证书加密了。访问http的时候会自动跳转到https上面。

server {
    listen ;
    server_name www.域名.com;
    rewrite ^(.*)$ https://${server_name}$1 permanent;
}
server {
    listen ;
    server_name www.域名.com;
    root /home/wwwroot;
    ssl on;
    ssl_certificate /etc/nginx/certs/server.crt;
    ssl_certificate_key /etc/nginx/certs/server.key;
    ....
}

备注: ${server_name}可以换成$host

二、重启nginx。

三、示例(以下是我们生产的配置)

server {
    listen ;
    server_name www.test.com;
    rewrite ^(.*)$ https://${server_name}$1 permanent;
}

server {
    listen ;
    server_name www.test.com;
    ssl on;
    ssl_certificate   /etc/pki/CA/certs/.pem;
    ssl_certificate_key  /etc/pki/CA/certs/.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. TLSv1.;
    ssl_prefer_server_ciphers on;
    index index.php index.htm index.html;
    error_page  /.html;
    error_page     /50x.html;

    location ~ \.php {
    root /alidata/www/html;
    fastcgi_pass unix:/tmp/php-cgi.sock;
    fastcgi_index index.php;
    include   fastcgi.conf;

    set $path_info "";
    set $fastcgi_script_name_new $fastcgi_script_name;

        if ($fastcgi_script_name ~*   "^(.+\.php)(/.+)$"  ) {
            ;
        ;
    }

    fastcgi_param   SCRIPT_FILENAME   $document_root$fastcgi_script_name_new;
    fastcgi_param   SCRIPT_NAME   $fastcgi_script_name_new;
    fastcgi_param   PATH_INFO $path_info;
    }

    location / {
    root /alidata/www/html;
    index index.php index.html index.htm;
    if (!-e  $request_filename){
        rewrite ^(.*)$ /index.php$ last;
    }
  }
}