如何在 nginx 中将所有 http 重定向到 https

如何在 nginx 中将所有 http 重定向到 https

这是我第一次使用 Nginx,我发现一些代码示例对我来说不起作用。

这是我的配置文件:

upstream myapp {
    server 127.0.0.1:3000;
    keepalive 8;
}

# the nginx server instance
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name weally.org www.weally.org;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    server_name weally.org www.weally.org;
    ssl_certificate     /etc/letsencrypt/live/weally.org/cert.pem;
    ssl_certificate_key /etc/letsencrypt/live/weally.org/privkey.pem;
    ssl_protocols       TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers         HIGH:!aNULL:!MD5;    access_log /var/log/nginx/weally.org.log;
    # add Strict-Transport-Security to prevent man in the middle attacks
    add_header Strict-Transport-Security "max-age=31536000" always;

    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://myapp/;
      proxy_redirect off;
    }
 }

如果给我这个日志:

root@ns3072230:~# systemctl status nginx.service
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Wed 2019-08-14 08:08:56 UTC; 10s ago
     Docs: man:nginx(8)
  Process: 3901 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx.pid (code=exited, status=0/SUCCESS)
  Process: 1578 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
  Process: 3902 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=1/FAILURE)
 Main PID: 1579 (code=exited, status=0/SUCCESS)

Aug 14 08:08:56 ns3072230 systemd[1]: Starting A high performance web server and a reverse proxy server...
Aug 14 08:08:56 ns3072230 nginx[3902]: nginx: [emerg] a duplicate default server for 0.0.0.0:80 in /etc/nginx/sites-enabled/default:22
Aug 14 08:08:56 ns3072230 nginx[3902]: nginx: configuration file /etc/nginx/nginx.conf test failed
Aug 14 08:08:56 ns3072230 systemd[1]: nginx.service: Control process exited, code=exited status=1
Aug 14 08:08:56 ns3072230 systemd[1]: nginx.service: Failed with result 'exit-code'.
Aug 14 08:08:56 ns3072230 systemd[1]: Failed to start A high performance web server and a reverse proxy server.
root@ns3072230:~# sudo vim /etc/nginx/conf.d/weally.org.conf 

我很惊讶,因为我在网上看到了很多例子,有很多服务器{}配置文件。

感谢您的帮助

答案1

来自评论:

您有 的多个配置default_server。请禁用默认站点,或更改服务器指令。我假设您已在和 中default_server设置,因此 nginx 检测到重复。/etc/nginx/sites-enabled/default/etc/nginx/conf.d/weally.org.conf

相关内容