www到非www重定向不适用于nginx上的https

时间:2017-04-11 15:29:19

标签: .htaccess redirect nginx

我正在尝试将所有网址重定向到example.com而不是www.example.com。当我输入www.example.com并点击进入重定向到https://domain.com时,它正在按预期工作。但是,当我输入https://www.example.com时,它将转到https://www.example.com,但我尝试将其重定向到https://example.com。我对类似的问题采取了一些解决方案,但没有奏效。以下是我的nginx配置文件。

upstream puma {
  server unix:///home/deploy/apps/myprod/shared/tmp/sockets/myprod-puma.sock;
}
server {
    listen 80;
    listen [::]:80;
    server_name example.com; 
    return 301 https://$server_name$request_uri;
}

server {
  #listen 80 default_server deferred;
  #listen 80;
  listen 443 default ssl;

  server_name domain.com;

  ssl_certificate /etc/nginx/ssl/domain.com.chained.crt;
  ssl_certificate_key /etc/nginx/ssl/domain.key;


  root /home/deploy/apps/myprod/current/public;
  access_log /home/deploy/apps/myprod/current/log/nginx.access.log;
  error_log /home/deploy/apps/myprod/current/log/nginx.error.log info;

  #location ^~ /assets/ {
    #gzip_static on;
    #expires max;
    #add_header Cache-Control public;
  #}

  location ^~ /(assets|fonts|swfs|images)/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  try_files $uri/index.html $uri @puma;
  location @puma {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;

    proxy_pass http://puma;
  }
}

请有人告诉我应该做些什么改变来实现这种非www重定向

1 个答案:

答案 0 :(得分:1)

尝试使用此server广告代码:

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

希望它会有所帮助。