Nginx + Certbot + Cloudflare重定向失败如何解决!

本网站采用hugo + nginx + certbot + cloudflare构建,记录一下遇到重定向失败的情况,具体操作如下:

在Cloudflare将网站解释到你的IP

Cloudflare地址解释
下面以mysite.com为例.

Debian 12安装nginx, certbot

1sudo apt update
2sudo apt install snapd
3sudo apt-get remove certbot
4sudo snap install --classic certbot

安装nginx

1sudo apt install nginx

配置网站

1cd /etc/nginx/sites-available
2touch mysite.com

将下面的代码粘贴到mysite.com文件

 1server {
 2       listen 80;
 3       listen [::]:80;
 4
 5       server_name mysite.com www.mysite.com;
 6
 7       root /home/username/mysite/public/; #Absolute path to where your hugo site is
 8       index index.html; # Hugo generates HTML
 9
10       location / {
11               try_files $uri $uri/ =404;
12       }
13}

建立链接到sites-enabled

1cd /etc/nginx/sites-enabled/
2ln -s ../sites-available/mysite.com site.com

启动nginx

1systemctl start nginx
2systemctl enable nginx

用certbot配置ssl

1certbot --nginx

完整的mysite.com如下:

 1server {
 2
 3       server_name mysite.com;
 4
 5       root /home/username/mysite/public/; #Absolute path to where your hugo site is
 6       index index.html; # Hugo generates HTML
 7
 8       location / {
 9               try_files $uri $uri/ =404;
10       }
11
12    listen [::]:443 ssl ipv6only=on; # managed by Certbot
13    listen 443 ssl; # managed by Certbot
14    ssl_certificate /etc/letsencrypt/live/mysite.com/fullchain.pem; # managed by Certbot
15    ssl_certificate_key /etc/letsencrypt/live/mysite.com/privkey.pem; # managed by Certbot
16    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
17    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
18
19}
20server {
21    if ($host = mysite.com) {
22        return 301 https://$host$request_uri;
23    } # managed by Certbot
24
25
26       listen 80;
27       listen [::]:80;
28
29       server_name mysite.com;
30    return 404; # managed by Certbot
31
32}

这时候,如果关闭Cloudflare的CDN功能,仅做DNS解释,网站正常, 但如果开启代理(Proxied),就会出现:

The Page Isn’t Redirecting Properly
这个页面重定向不正确!

这个问题以前也遇到过,当时只用DNS就上线了,今天花了点时间找解决方案,也做了不同的尝试, 最后在cloudflare的SSL设置选择Full,就可以了!

Cloudflare SSL设置