配置HTTPS重定向失败

时间:2020-02-13 07:56:22

标签: django ssl nginx hosting

我正在digitalocean上托管Django应用程序。我遵循this tutorial完成其SSL认证。在该教程之后,我不知道在哪里添加以下代码行:

return 301 https://$server_name$request_uri;

我尝试将其添加到/etc/nginx/sites-enabled/leptitox_pro

server {
    listen 80;
    server_name 68.183.203.33 yahkut.com www.yahkut.com;
    return 301 https://$server_name$request_uri;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/leptitoxadmin/pyapps/Leptitox;
    }

    location /media/ {
        root /home/leptitoxadmin/pyapps/Leptitox;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

当它不起作用时,我将其添加到/etc/nginx/sites-available/leptitox_pro

server {
    listen 80;
    server_name 68.183.203.33 yahkut.com www.yahkut.com;
    return 301 https://$server_name$request_uri;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/leptitoxadmin/pyapps/Leptitox;
    }

    location /media/ {
        root /home/leptitoxadmin/pyapps/Leptitox;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/run/gunicorn.sock;
    }
}

它在那里也不能正常工作,因此我在/etc/nginx/nginx.conf的服务器代码块下面添加了:

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
        worker_connections 768;
        # multi_accept on;
}

http {
        server {                                           # new
          listen 80;                                       # new
          server_name yahkut.com;                          # new
          return 301 https://$server_name$request_uri;     # new
        }

        ##
        # Basic Settings
        ##

        sendfile on;
        tcp_nopush on;
}

然后我重新启动ngnix并运行nginx -t并收到一条成功消息,当我运行该网站时,我得到404 not found或网站的非安全版本。 请帮我解决一下这个。谢谢

2 个答案:

答案 0 :(得分:0)

您必须将运行端口80的服务器块和运行端口443(SSL)的服务器块分开。就是这样:

Trans

答案 1 :(得分:0)

添加这些服务器块。

这是将http重定向到https

server {
   listen 80;
   server_name example.com; 
   location / {
          return 301 https://$host$request_uri;
   }
}

您的带有ssl的主块

server {
    listen 443 ssl ;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; 
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;  
    index index.html index.htm index.nginx-debian.html;
    server_name example.com; 
    location / {
    proxy_pass http://localhost:5003; // Your port goes here
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}
}

位于/ nginx / sites-enabled / default下,或者您可以在此文件夹中为其创建其他文件