Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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>
  }
share|improve this question
    
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
add comment

1 Answer 1

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;
}
share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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