将 HTTP 从 Nginx 重定向到 HTTPS 不起作用

Huu*_*ang 1 ssl https nginx

输入:https : //example.com => ssl ok 但是输入:www.example.com 和 example.com 是 http没有重定向https。(www 重定向到非 www)。

WordPress 地址 (URL) 和站点地址 (URL):https//example.com

/etc/nginx/conf.d/example.com.conf

server {
listen 80; 
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
server_name example.com www.example.com;
ssl on;
ssl_certificate /etc/nginx/ssl/cert_chain.crt;
#ssl_CACertificate_File /etc/nginx/ssl/example.com.ca-bundle;
ssl_certificate_key /etc/nginx/ssl/example.com.key; 
access_log off;
# access_log /home/example.com/logs/access_log;
error_log off;
# error_log /home/example.com/logs/error.log; 
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
root /home/example.com/public_html;
include /etc/nginx/conf/ddos2.conf;
index index.php index.html index.htm;
server_name example.com;
Run Code Online (Sandbox Code Playgroud)

如何解决?对不起,我的英语不好,谢谢。

Hee*_*aaw 5

这可能确实是由不明确的服务器名称引起的。尝试使用以下方法:

server {

    server_name example.com www.example.com;
    listen 80;
    listen 443 ssl; # Listen for SSL at port 443 as well

    # ... other config - certificates and such

    # If a user tries to come through http, redirect them through https
    if ($scheme != "https") { 
        return 301 https://$host$request_uri;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以通过运行来检查您的 nginx 配置sudo nginx -t


小智 5

我有类似的问题。这是由于linux防火墙(不允许80端口)引起的。