使用 Nginx 将 http 重定向到 https

redirect http to https by using Nginx

我的 Nginx 配置如下:

server {
        listen 80;
        server_name my-domain.co.id;
        listen 443 ssl;
        return 301 https://$server_name$request_uri;
        ssl_certificate /etc/ssl/certs/project_chained2022.crt;
        ssl_certificate_key /etc/ssl/private/pkey2022.key;
        location / {
            proxy_pass http://localhost:54444;
            proxy_redirect     off;
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Host $server_name;

        }
}

我尝试使用 return 301 https://$server_name$request_uri 重定向,但它不起作用。

还有其他方法可以进行重定向吗?

您需要使用两个server块,例如:

server {
    listen 80;
    server_name my-domain.co.id;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name my-domain.co.id;

    ssl_certificate ...;
    ssl_certificate_key ...;
    ...
}