简体   繁体   English

NGINX 重定向 http 到 https 不起作用

[英]NGINX redirect http to https is not working

I was trying to set up a wordpress web server using nginx on my own laptop.我试图在我自己的笔记本电脑上使用 nginx 设置 wordpress web 服务器。 The certificate was installed successfully and I can visit my site through https.证书安装成功,我可以通过https访问我的站点。 However, I found out that the redirecting from http to https is not working.但是,我发现从 http 到 https 的重定向不起作用。 My site always showed 400 Bad Request when I tried to visit through http.当我尝试通过 http 访问时,我的网站总是显示400 Bad Request Lots of answers on Google say that this can be fixed by commenting out "ssl on" but actually I don't have this line in my code.谷歌上的很多答案都说这可以通过注释掉“ssl on”来解决,但实际上我的代码中没有这一行。

server {
    root /var/www/html;
    index index.php index.html index.htm;
    server_name mydomain.com;

    location / {
            try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

    location ~ /\.ht {
            deny all;
    }

listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot             
}

server {
    if ($host = mydomain.com) {
    return 301 https://$host$request_uri;

    } # managed by Certbot


    listen 80 default_server;
    server_name mydomain.com;
    return 404; # managed by Certbot
 }

I found out the problem was coming from my NAT setting.我发现问题来自我的 NAT 设置。 The external 80 and 443 connections were forwarded to my internal server's port 443 under 1 NAT rule.在 1 NAT 规则下,外部 80 和 443 连接被转发到我的内部服务器的端口 443。 After separating 80 and 443 to different rules and everything works!将 80 和 443 分成不同的规则后,一切正常!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM