如何强制全站https访问

今天在阿里云上搞了一个免费的https证书,于是就在自己的服务器上安装了一下,配置好证书之后,如何强制全站https访问呢?其实方法有很多,这里只给出两个比较简单的方法:

#在自己的虚拟主机配置server节点中添加下面的代码,使用其一即可。
#方法一
rewrite ^ https://$server_name$request_uri? permanent;
#方法二
return 301 https://$server_name$request_uri;

我用的是第一个方法,大家可以根据自己的喜好,来决定使用哪中方法。下面贴出我自己网站的配置:

server {
    listen     443;
    listen     80;
    
    server_name  www.ydstudio.net;
    set $my_server_name $scheme://$server_name;
    
    #防止ip访问,如http://xxx.xxx.xxx.xxx或者https://xxx.xxx.xxx.xxx
    if ( $host ~* "\d+\.\d+\.\d+\.\d+" ) {
        rewrite ^ https://$server_name;
    }
    
    if ( $my_server_name != https://$server_name ) {
       rewrite ^ https://$server_name$request_uri? permanent;
    }
    
    location / {
       root   /usr/share/nginx/html/typecho/;
       try_files $uri $uri/ /index.php$is_args$args;
       index index.php  index.html index.htm;
    }
   
    #error_page  404              /404.html;
    # redirect server error pages to the static page /50x.html
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
    # proxy the PHP scripts to Apache listening on 127.0.0.1:80
    #location ~ \.php$ {
    #    proxy_pass   http://127.0.0.1;
    #}
    # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
    location ~ \.php$ {
       #root           html;
       fastcgi_pass   127.0.0.1:9000;
       fastcgi_index  index.php;
       fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html/typecho/$fastcgi_script_name;
       include        fastcgi_params;
    }
    # deny access to .htaccess files, if Apache's document root
    # concurs with nginx's one
    #location ~ /\.ht {
    #    deny  all;
    #}
    ssl on;
    ssl_certificate   /etc/nginx/cert/214353452860792.pem;
    ssl_certificate_key  /etc/nginx/cert/214353452860792.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;
}

相关文章

此处评论已关闭