2

I can't seem to redirect my https://www to https:// How it is currently the site thinks that www. is a completely separate site. I want to redirect properly, but when I add configuration on what I think is correct I get an infinite redirect. Non-https www redirects properly. Only issue is https://www.

Here is my nginx config, maybe I am just missing something. I removed the https://www redirect because I can't seem to get it right.

server {
    listen 192.168.0.123:80;
    server_name www.site.com site.com;

    location /rss/main/ {
            uwsgi_pass unix:///tmp/site.com.sock;
            include uwsgi_params;
    }

    location / {
            rewrite ^ https://site.com$request_uri permanent;
    }

}
server {
        listen 192.168.0.123:443 ssl;
        server_name site.com;
        access_log /var/log/nginx/site.com_access.log;
        error_log /var/log/nginx/site.com_error.log;

        ssl_certificate /srv/ssl/site_com.crt;
        ssl_certificate_key /srv/ssl/site.com.key;

        location / {
                uwsgi_pass unix:///tmp/site.com.sock;
                include uwsgi_params;
        }

        location /static/ {
                alias /var/www/site.com/static_final/;
        }

        location /media/ {
                alias /var/www/assets/site/;
    }
}

Any help is appreciated as I don't want people to accidentally access the www.

quanta
  • 51,413
  • 19
  • 159
  • 217
Buddy Lindsey
  • 269
  • 3
  • 9

2 Answers2

3

I assume your SSL certificate covers both www.site.com and site.com. The following would appear to be the most appropriate way of handling this?

server {
        listen 192.168.0.123:443 ssl;
        server_name www.site.com;

        ssl_certificate /srv/ssl/site_com.crt;
        ssl_certificate_key /srv/ssl/site.com.key;

        rewrite ^ https://site.com$request_uri permanent;
}
Alan
  • 189
  • 1
  • 7
2

For a simple 301 redirect, we could use return directive.

server {
        listen 192.168.0.123:443 ssl;
        server_name www.site.com;

        ssl_certificate /srv/ssl/site_com.crt;
        ssl_certificate_key /srv/ssl/site.com.key;

        return 301 $scheme://site.com$request_uri;
}

This is effectively the same as Alan's answer, but by using the return directive we can completely avoid evaluation of regular expression.

Michael Hampton
  • 244,070
  • 43
  • 506
  • 972
Pothi Kalimuthu
  • 6,117
  • 2
  • 26
  • 38