首页 > 解决方案 > Nginx 不会重定向到 www

问题描述

您好,我很难正确配置 nginx。我想从https://example.com重定向到https://www.example.com我发现很多教程如何做到这一点,但没有一个与我的配置文件一起使用。我使用letsencrpyt 为我配置SSL。这是 nginx 配置文件:

server {
  server_name IP_ADDRESS example.com www.example.com;

  location /static/ {
      root /home/user/pyapps/ks_g;
  }

  location /media/ {
      root /home/user/pyapps/ks_g;    
  }

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

  listen 443 ssl; # managed by Certbot
  ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem; # managed by Certbot
  ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem; # managed by Certbot
  include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
  ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
   if ($host = www.example.com) {
      return 301 https://$host$request_uri;
   } # managed by Certbot 

   listen 80;
   server_name IP_ADDRESS example.com www.example.com;
   return 404; # managed by Certbot
 }

标签: nginxurlredirect

解决方案


使用 SSL 或两者都将重定向条件添加到服务器块:

   if ($host != www.example.com) {
      return 301 https://www.example.com$request_uri;
   } # managed by Stack Overflow (sorry cannot hold myself)

其工作原理如下:如果HostHTTP 标头不等于www.example.com,则永久重定向到https://www.example.com$request_uri.


推荐阅读