如何强制 Nginx 将全站转向 WWW 和 HTTPS,


本文最先发布在:

https://www.itcoder.tech/posts/how-to-force-nginx-redirect-to-www-and-https/

一、简介

如何强制 Nginx 将全站转向 WWW 和 HTTPS?

下面我们以域名 example.com 进行举例,我们的目标是:

  1. http://example.com -> https://www.example.com
  2. https://example.com -> https://www.example.com
  3. http://www.example.com -> https://www.example.com
  4. https://www.example.com

二、如何强制 Nginx 将全站转向 WWW 和 HTTPS

01.在 /etc/nginx/conf.d目录下,新建配置文件example.com.conf

02.将下面的配置内容,拷贝到新建的配置文件中,保存并退出。

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name example.com www.example.com;

    return 301 https://www.example.com$request_uri;
}


server {
    listen *:443 ssl; 
    listen [::]:443 ssl; 
    server_name example.com;

    return 301 https://www.example.com$request_uri;
}

server {
    listen *:443 ssl http2; 
    listen [::]:443  ssl http2; 
    server_name www.example.com;      
              
    add_header Strict-Transport-Security "max-age=63072000; includeSubdomains; preload";
    add_header X-Frame-Options "DENY";

    charset utf8;

    access_log  /var/log/nginx/*.example.com/access.log  main;
    error_log  /var/log/nginx/*.example.com/error.log warn;

    location / {
        root   /root/itcoder/public;
        index  index.html index.htm;
    }

    # ssl on;
    ssl_certificate /etc/nginx/ssl/*.example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/*.example.com.key;
    ssl_session_timeout  5m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4:!DH:!DHE;
    ssl_prefer_server_ciphers  on;

    error_page  404              /404.html;
#    location = /404.html {
 #       root   /usr/share/nginx/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;
    }
}

03.运行下面的命令,检测配置文件是否合规:

nginx -t

如果配置文件没有语法错误,一般会提示如下:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

04.重新加载 Nginx 配置文件,使修改生效。

nginx -s reload

或者

systemctl reload nginx

三、总结

本站经过改造,已经强制 Nginx 将全站转向 WWW 和 HTTPS,欢迎体验。

  1. http://itcoder.tech -> https://www.itcoder.tech
  2. https://itcoder.tech -> https://www.itcoder.tech
  3. http://www.itcoder.tech -> https://www.itcoder.tech
  4. https://www.itcoder.tech

四、参考文档

  1. Redirect HTTP to HTTPS in Nginx
  2. Redirect all HTTP requests to HTTPS with Nginx
  3. Best way to redirect all HTTP requests to HTTPS with Nginx

相关内容