nginx下配置域名301重定向和强制访问https

介绍一下如何在军哥lnmp下配置域名301重定向和强制访问https。

301重定向

首先打开你的域名配置文件

vi /usr/local/nginx/conf/vhost/你的域名.conf

清楚全部内容,修改为下面内容(其实域名自行替换)

server 
    {
        listen 80;
        server_name abc.com;
        return 301 http://xyz.com$request_uri;
    }

然后重启nginx即可

service nginx restart

启用ssl后,强制访问https

强制访问https,这里是通过301重定向来实现的,这种方式比较推荐。
和上面一样,打开域名配置文件,修改为下面内容(其中域名、证书路径、网站目录、伪静态文件自行根据实际情况修改一下)

server
    {
        listen 443 ssl http2;
        #listen [::]:443 ssl http2;
        server_name abc.com ;
        index index.html index.htm index.php default.html default.htm default.php;
        root  /home/wwwroot/abc.com;                 
        ssl on;
        ssl_certificate /home/www/abc.com.crt;
        ssl_certificate_key /home/www/abc.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 wordpress.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.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;
    }
server 
    {
        listen 80;
        server_name abc.com;
        return 301 https://abc.com$request_uri;
    }

配置完成后,重启nginx

service nginx restart

发表评论