Nginx没有将流量从http重定向到https

时间:2019-04-04 19:22:49

标签: amazon-web-services nginx amazon-ec2 amazon-linux

我在Amazon Linux 2的EC2服务器上安装了nginx,并通过HTTP和HTTPS服务我的网站。但是,我无法使位置块在HTTP上运行。如果我需要提供文件或重定向到proxy_path,它们可以在HTTPS上完美运行,但是不适用于HTTP。

我想将所有流量从HTTP重定向到HTTPS。

此外,即使我删除了第一个服务器块,仍然可以通过端口80来访问网站。

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

这是我的完整Nginx配置文件,位于/etc/nginx/nginx.conf

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    #include /etc/nginx/conf.d/*.conf;

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

    server {
        listen 443 ssl;

        server_name *.example.com;

        ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

        location /.well-known/acme-challenge/test {
                return 200 'test.test';
        }
        location / {
            proxy_pass http://localhost:5000;
            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是否使用默认配置文件?

2 个答案:

答案 0 :(得分:0)

您的http块应如下所示:

server {
    listen 80;
    server_name *.example.com;

    location / {
        return 301 https://$host$request_uri;
    }
}

答案 1 :(得分:0)

我解决了这个问题。主要问题是另一个进程将请求缓存并在主机上运行并在端口80和443上侦听。杀死了该进程,一切正常。