不带www跳转带www
强制HTTPS跳转

本文仅记录在使用Typecho时可以使用的方法,关于nginx中301重定向的写法有许多,甚至性能都有差距,本文收集的方法不是最高效的但是亲测有用.如果域名套了Cloudflare,在Crypto就可以设置https的强制跳转.

不带www跳转带www

为社么要这么跳转呢,明明主域名就可以访问啊,因为闲的,总感觉带www是完整的体现
编辑vhost的nginx配置文件在server{}中最下面添加一段if语句即可

vi /usr/local/nginx/conf/vhost/j000e.com.conf
#添加在最下面}之前添加如下
if ($host != 'www.j000e.com'){
        rewrite ^/(.*)$ https://www.j000e.com/$1 permanent;
        }
#完整配置文件如下
server
    {
        listen 443 ssl http2;
        #listen [::]:443 ssl http2;
        server_name www.j000e.com j000e.com;
        index index.html index.htm index.php default.html default.htm default.php;
        root  /home/wwwroot/joooe.xyz;
        ssl on;
        ssl_certificate /home/wwwroot/j000e.com.pem;
        ssl_certificate_key /home/wwwroot/j000e.com.key;
        ssl_session_timeout 5m;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        ssl_ciphers "EECDH+CHACHA20:EECDH+CHACHA20-draft:EECDH+AES128:RSA+AES128:EECDH+AES256:RSA+AES256:EECDH+3DES:RSA+3DES:!MD5";
        ssl_session_cache builtin:1000 shared:SSL:10m;
        # openssl dhparam -out /usr/local/nginx/conf/ssl/dhparam.pem 2048
        ssl_dhparam /usr/local/nginx/conf/ssl/dhparam.pem;

        include rewrite/typecho.conf;
        #error_page   404   /404.html;

        # Deny access to PHP files in specific directory
        #location ~ /(wp-content|uploads|wp-includes|images)/.*\.php$ { deny all; }

        include enable-php-pathinfo.conf;

        location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
        {
            expires      30d;
        }

        location ~ .*\.(js|css)?$
        {
            expires      12h;
        }

        location ~ /.well-known {
            allow all;
        }

        location ~ /\.
        {
            deny all;
        }

        access_log off;

        if ($host != 'www.j000e.com'){
        rewrite ^/(.*)$ https://www.j000e.com/$1 permanent;
        }
    }

修改完重启lnmp

lnmp restart

强制HTTPS跳转

编辑vhost的nginx配置文件,在末尾单独添加一server{}段

vi /usr/local/nginx/conf/vhost/j000e.com.conf
#添加如下
server
{
        listen 80;
        server_name j000e.com www.j000e.com;
        rewrite ^(.*) https://www.j000e.com$1 permanent;
}

完整配置文件大概如下(我并没实际添加此段)

server {
listen 443;
ssl on;
ssl_certificate /data/ssl/j000e.com.crt;
ssl_certificate_key /data/ssl/j000e.com.key;
server_name j000e.com www.j000e.com;
index index.html index.htm index.php;
...
...
}

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

修改完重启lnmp

lnmp restart
THE END
最后修改:2018 年 08 月 09 日 22 : 54
本文链接:https://www.j000e.com/linux/nginx301.html
版权声明:本文『Nginx强制HTTPS301重定向,不带www的域名跳转带www的』为『Joe』原创。著作权归作者所有。
转载说明:Nginx强制HTTPS301重定向,不带www的域名跳转带www的 || Joe's Blog』转载许可类型见文末右下角标识。允许规范转载时,转载文章需注明原文出处及地址。
Last modification:August 9, 2018
If you think my article is useful to you, please feel free to appreciate