简体   繁体   English

Nginx - 将 HTTP 重定向到 HTTPS

[英]Nginx - Redirect HTTP to HTTPS

I have followed some tutorials on setting up a .Net Core server on Lightsail as well as how to set up SSL for Nginx, resulting in the following 'default' config file:我遵循了一些关于在 Lightsail 上设置 .Net Core 服务器以及如何为 Nginx 设置 SSL 的教程,从而生成了以下“默认”配置文件:

server {
    listen 80 http2 default_server;
    root /var/www/mywebsite/wwwroot;
    server_name mywebsite.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    root /var/www/mywebsite/wwwroot;
    ssl_certificate /etc/letsencrypt/live/www.mywebsite.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/www.mywebsite.com/privkey.pem;
    location / {
        proxy_pass http://localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep-alive;
        proxy_set_header Host $http_host;
        proxy_cache_bypass $http_upgrade;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

I am currently able to connect to https://mywebsite.com and https://www.mywebsite.com , but when I try to go to the http versions, either nothing is found, or on chrome a file is downloaded with a few strange characters.我目前可以连接到https://mywebsite.comhttps://www.mywebsite.com ,但是当我尝试访问 http 版本时,要么什么也没找到,要么在 chrome 上下载了一个文件几个奇怪的字符。 Any help with this would be greatly appreciated.对此的任何帮助将不胜感激。

Try this:

    
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com; 
    return 301 https://example.com$request_uri;
}

server {
    listen 443 ssl;
    listen [::]:443 ssl;
    server_name www.example.com; 
    ssl on;
}

The error seemed to be caused by browsers only supporting HTTP/2 with SSL.该错误似乎是由仅支持带 SSL 的 HTTP/2 的浏览器引起的。 This isn't a problem in my case because I am redirecting to the secure site, so changing line 1 of the first server block from在我的情况下这不是问题,因为我正在重定向到安全站点,因此将第一个服务器块的第 1 行从

listen 80 http2;

to

listen 80;

Solved my problem and now the redirect works.解决了我的问题,现在重定向有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM