nginx 上的 http 到 https 重定向 [英] http to https redirection on nginx

查看:100
本文介绍了nginx 上的 http 到 https 重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 Amazon ELB 后面的 EC2 机器上运行的网站.
我已经在 ELB 上配置了 SSL,因此它可以为我处理 http 和 https.https 上的所有请求都可以完美运行.但我想强制(重定向)http 请求到 https.由于某种原因,它不起作用

I have a website running on EC2 machine behind an Amazon ELB.
I have configured SSL on ELB hence its handling http as well as https for me. All requests on https works perfectly. But I want to force(redirect) http requests to https. For some reason, it does not work

我在 nginx 中添加了重定向规则,但是每当我启用该规则时,nginx 服务器就会停止响应.

I have added redirect rule in nginx but whenever I enable that rule, the nginx server stops responding.

server {
listen 80;
server_name domain1.com;
gzip on;
gzip_proxied any;
gzip_types text/plain text/xml text/css application/x-javascript;
gzip_vary on;

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

location / {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass    http://127.0.0.1:4000/;
   ###  Redirect http to https ####
   if ($http_x_forwarded_proto != "https") {
    rewrite ^(.*)$ https://$server_name$1 permanent;
   }
   add_header Strict-Transport-Security "max-age=31536000; includeSubDomains;";
}
}

这里是负载均衡器的配置:

Here is the configuration of Load Balancer:

请帮助我配置哪里出错了.TIA.

Please help me where I am going wrong with the configuration. TIA.

推荐答案

我提出这个代码.在我的 VPS 上测试,而不是 Amazon ELB

I propose this code. Teste on my VPS, but not Amazon ELB

server {
server_name example.com www.example.com;
        listen 80;
        return 301 https://example.com$request_uri;
}
server {
server_name example.com;
        root /home/user/www/example/;
        include global.conf;
        include php.conf;
        include ssl.conf;
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

}
server{
server_name www.example.com;
        include ssl.conf;
        return 301 https://example.com$request_uri;
        ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
}

文件 ssl.conf 包含:

File ssl.conf containt:

listen 443 ssl http2;
listen [::]:443 ssl http2;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-DSS-AES128-GCM-SHA256:kEDH+AES$
ssl_session_timeout 1d;
ssl_session_cache shared:SSL:50m;
ssl_stapling on;
ssl_stapling_verify on;
add_header Strict-Transport-Security max-age=15768000;

这篇关于nginx 上的 http 到 https 重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆