user3576036
user3576036

Reputation: 1425

www to non www redirect is not working for https on nginx

I am trying to redirect all the urls to example.com instead of www.example.com. It is working as expected when I type www.example.com and hit enter its redirecting to https: //domain.com. But when I type https: //www.example.com it is going to https: //www.example.com but I am trying to redirect it to https: //example.com. I followed some solutions to similar questions but didn't work. Following is my nginx config file.

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;
  }
}

Please can somebody tell what changes should I make to achieve this non www redirect

Upvotes: 0

Views: 95

Answers (1)

Manish Nagdewani
Manish Nagdewani

Reputation: 597

Try using this server block code:

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

Hope it would help.

Upvotes: 1

Related Questions