0

I would like all traffic without the www, including https, to be redirected to the respective url with the www.

So http://example.com -> http://www.example.com, https://example.com -> https://www.example.com

There's plenty of info online about forcing ssl, which I do not want to do, and forcing www, but only for http. Just adding an s and changing the listen 80 -> listen 443 breaks the http sites. Here's my config so far:

  server {
    listen  80;
    server_name example.com;
    location / {
      rewrite  ^/(.*)$  http://www.example.com/$1  permanent;
    }
  }

  server {
    listen   80;
    server_name www.example.com;
    root   /opt/example;
    index  index.html;

    <locations stuff>
  }

  server {
    listen  443;
    server_name example.com;
    ssl                   on;
    ssl_certificate       /opt/nginx/ssl/server.crt;
    ssl_certificate_key   /opt/nginx/ssl/server.key;
    location / {
      rewrite  ^/(.*)$  https://www.example.com/$1  permanent;
    }
  }

  server {
    listen  443;
    server_name www.example.com;
    root   /opt/example;

    ssl                   on;
    ssl_certificate       /opt/nginx/ssl/server.crt;
    ssl_certificate_key   /opt/nginx/ssl/server.key;

    <locations stuff>
  }
  • Adding an s where? Breaks the http sites how? – Shane Madden Oct 23 '11 at 4:43
  • Sorry adding an s after http in the rewrite rule. Basically it does not respond to http requests. – jhchen Oct 23 '11 at 5:00
3

This is a stripped down version of my own config, which I think does what you want:

server {
    listen 80  default;
    listen 443 default ssl;
    server_name *.example.com;

    if ($host = example.com) {
        rewrite ^(.*) $scheme://www.example.com$1 permanent;
    }

    root   /opt/example;

    ssl                   on;
    ssl_certificate       /opt/nginx/ssl/server.crt;
    ssl_certificate_key   /opt/nginx/ssl/server.key;
}
  • i was looking for this way of doing it thanks, i like it because you only use one server block – Hayden Thring Jan 21 '13 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.