【问题标题】:Nginx Redirect all to https and non www - redirect loopNginx 将所有重定向到 https 和非 www - 重定向循环
【发布时间】:2015-09-12 22:59:54
【问题描述】:

我正在尝试将 server_name 的所有非 http 和 www 流量重定向到 https://example.com。我有以下问题:

  1. http://www.example.com 的任何请求都不会被重定向;
  2. 对 http://example.com 的任何请求都会出现错误 400;
  3. 任何对 https 的请求都会进入 301 重定向循环。

我已经尝试了使用单独的服务器块的多种变体,最接近的方法是让它全部正常工作,除了重定向循环,无论我做什么都会困扰我。在这里不胜感激一些建议和指示。代码如下:

server {
   listen         443;
   listen         80;
   server_name    www.example.com example.com;

root /home/example/public_html;
index index.html index.htm index.php;

#SSL Stuff here

if ($scheme = http) { return 301 https://example.com$request_uri; }
if ($server_name = www.example.com) { return 301 https://example.com$request_uri; }

include conf.d/wp/restrictions.conf;
include conf.d/wp/wordpress.conf;
}
编辑

所以我尝试了以下方法,除了 http 之外没有 301 循环,所有这些都可以正常工作://www.example.com 允许通过而不重定向到 SSL。我不明白这怎么可能,因为它应该被端口 80 规则捕获,不是吗?更新配置如下:

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

################# SECURE #################

server {
listen   443;
server_name example.com;
access_log /var/log/nginx/example-ssl.access.log;
error_log /var/log/nginx/example-ssl.error.log;

root /home/example/public_html;
index index.html index.htm index.php;

# SSL Stuff here

#include conf.d/wp/restrictions.conf;
#include conf.d/wp/wordpress.conf;
}

【问题讨论】:

    标签: redirect nginx https rewrite


    【解决方案1】:

    您的配置存在一些问题。

    1. 我会将$server_name 替换为$host 或对域进行硬编码 你想要的,比如“secondexample.com$request_uri
    2. 您在server 443 行中缺少ssl 标记。

    配置:

    server {
       listen         80;
       server_name    example.com;
       server_name    www.example.com;
       return 301 https://$host$request_uri;
    }
    
    ################# SECURE #################
    
    server {
       listen   443 ssl;
       server_name example.com;
       access_log /var/log/nginx/example-ssl.access.log;
       error_log /var/log/nginx/example-ssl.error.log;
    
       root /home/example/public_html;
       index index.html index.htm index.php;
    
       # SSL Stuff here
    
       #include conf.d/wp/restrictions.conf;
       #include conf.d/wp/wordpress.conf;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-03-08
      • 1970-01-01
      • 2017-03-10
      • 2018-04-22
      • 1970-01-01
      • 2016-01-07
      • 2018-06-23
      相关资源
      最近更新 更多